feat(shorts): keep modal draft and close only via cancel

This commit is contained in:
dev
2026-10-22 22:45:56 +03:00
parent af65b8f3eb
commit 816e7b2e38
2 changed files with 105 additions and 5 deletions
+104 -5
View File
@@ -1,6 +1,7 @@
async function init() {
if (!(await checkAuth())) return;
buildSidebar('shorts');
pruneShortsDrafts();
document.getElementById('addShortsBtn').addEventListener('click', () => openShortsModal(null));
document.getElementById('shortsViewToggle').addEventListener('click', e => {
@@ -9,7 +10,7 @@ async function init() {
setShortsViewMode(btn.dataset.mode);
});
syncShortsViewMode();
document.getElementById('shortsCancel').addEventListener('click', closeModal);
document.getElementById('shortsCancel').addEventListener('click', () => closeModal(true));
document.getElementById('shortsSave').addEventListener('click', saveShorts);
document.getElementById('shortsClearBtn').addEventListener('click', resetShortsFilters);
@@ -17,9 +18,11 @@ async function init() {
const at = document.getElementById('shortsUsedAt');
if (e.target.checked && !at.value) at.value = todayIso();
if (!e.target.checked) at.value = '';
scheduleShortsDraft();
});
document.getElementById('shortsUsedAt').addEventListener('change', e => {
document.getElementById('shortsModalUsed').checked = !!e.target.value;
scheduleShortsDraft();
});
document.getElementById('shortsAiBtn').addEventListener('click', openShortsAi);
@@ -31,6 +34,7 @@ async function init() {
const btn = e.target.closest('[data-delta]');
if (!btn) return;
setShortsDelta(parseInt(btn.dataset.delta, 10));
scheduleShortsDraft();
});
['shortsGroup', 'shortsDateFrom', 'shortsDateTo', 'shortsUsedFilter', 'shortsDeltaFilter', 'shortsOrder'].forEach(id => {
@@ -49,13 +53,17 @@ async function init() {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); saveShorts(); }
});
document.getElementById('shortsModal').addEventListener('click', e => { if (e.target.id === 'shortsModal') closeModal(); });
['shortsDate', 'shortsTopic', 'shortsResident', 'shortsLines', 'shortsUsedAt'].forEach(id => {
document.getElementById(id).addEventListener('input', scheduleShortsDraft);
document.getElementById(id).addEventListener('change', scheduleShortsDraft);
});
document.getElementById('aiCorrectModal').addEventListener('click', e => { if (e.target.id === 'aiCorrectModal') closeShortsAi(); });
document.addEventListener('keydown', e => {
if (e.key !== 'Escape') return;
if (document.getElementById('aiCorrectModal').classList.contains('open')) { closeShortsAi(); return; }
if (document.getElementById('shortsModal').classList.contains('open')) closeModal();
});
window.addEventListener('beforeunload', saveShortsDraft);
await loadShortsGroups();
connectShortsLive();
@@ -128,6 +136,80 @@ function currentShortsUser() {
try { return (typeof currentUser !== 'undefined') ? currentUser : null; } catch (e) { return null; }
}
const SHORTS_DRAFT_PREFIX = 'shortsDraft:';
let shortsDraftTimer = null;
let shortsDraftBaseline = null;
function shortsDraftKey() {
const u = currentShortsUser();
return SHORTS_DRAFT_PREFIX + (u && u.id ? u.id : 'anon') + ':' + (editingId ? 'edit' + editingId : 'new');
}
function pruneShortsDrafts() {
const u = currentShortsUser();
const prefix = SHORTS_DRAFT_PREFIX + (u && u.id ? u.id : 'anon') + ':';
const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
try {
for (let i = localStorage.length - 1; i >= 0; i--) {
const key = localStorage.key(i);
if (!key || !key.startsWith(prefix)) continue;
let d = null;
try { d = JSON.parse(localStorage.getItem(key)); } catch (e) {}
if (!d || !d.savedAt || d.savedAt < cutoff) localStorage.removeItem(key);
}
} catch (e) {}
}
function shortsDraftSnapshot() {
return {
editingId,
date: document.getElementById('shortsDate').value,
topic: document.getElementById('shortsTopic').value,
resident: document.getElementById('shortsResident').value,
lines: document.getElementById('shortsLines').value,
used: document.getElementById('shortsModalUsed').checked,
usedAt: document.getElementById('shortsUsedAt').value,
delta: shortsDelta
};
}
function readShortsDraft() {
try {
const raw = localStorage.getItem(shortsDraftKey());
if (!raw) return null;
const d = JSON.parse(raw);
return d && typeof d === 'object' ? d : null;
} catch (e) { return null; }
}
function shortsDraftEmpty(d) {
if (!d) return true;
return !String(d.topic || '').trim() && !String(d.lines || '').trim() && !String(d.resident || '').trim();
}
function saveShortsDraft() {
if (!document.getElementById('shortsModal').classList.contains('open')) return;
const d = shortsDraftSnapshot();
try {
if (shortsDraftEmpty(d) || JSON.stringify(d) === shortsDraftBaseline) localStorage.removeItem(shortsDraftKey());
else localStorage.setItem(shortsDraftKey(), JSON.stringify({ ...d, savedAt: Date.now() }));
} catch (e) {}
}
function scheduleShortsDraft() {
if (shortsDraftTimer) clearTimeout(shortsDraftTimer);
shortsDraftTimer = setTimeout(() => {
shortsDraftTimer = null;
saveShortsDraft();
}, 250);
}
function clearShortsDraft() {
if (shortsDraftTimer) { clearTimeout(shortsDraftTimer); shortsDraftTimer = null; }
shortsDraftBaseline = null;
try { localStorage.removeItem(shortsDraftKey()); } catch (e) {}
}
function isTutorOrAdmin() {
const u = currentShortsUser();
return !!(u && (u.role === 'admin' || u.role === 'tutor'));
@@ -424,9 +506,22 @@ function openShortsModal(row) {
setShortsDelta(0);
}
document.getElementById('shortsLines').value = row ? (row.message || '') : '';
shortsDraftBaseline = JSON.stringify(shortsDraftSnapshot());
const draft = readShortsDraft();
const restored = !!(draft && (draft.editingId || null) === editingId && !shortsDraftEmpty(draft));
if (restored) {
document.getElementById('shortsDate').value = draft.date || document.getElementById('shortsDate').value;
document.getElementById('shortsTopic').value = draft.topic || '';
document.getElementById('shortsResident').value = draft.resident || '';
document.getElementById('shortsLines').value = draft.lines || '';
document.getElementById('shortsModalUsed').checked = !!draft.used;
document.getElementById('shortsUsedAt').value = draft.usedAt || '';
if (row && isTutorOrAdmin()) setShortsDelta(Number(draft.delta || 0));
}
updateShortsLinesCount();
document.getElementById('shortsModal').classList.add('open');
setTimeout(() => document.getElementById('shortsLines').focus(), 40);
if (restored) showToast('Восстановлен сохранённый черновик');
renderIcons();
}
@@ -437,8 +532,11 @@ function updateShortsLinesCount() {
el.textContent = n ? `Строк: ${n}` : '';
}
function closeModal() {
function closeModal(keepDraft) {
if (keepDraft) saveShortsDraft();
else clearShortsDraft();
document.getElementById('shortsModal').classList.remove('open');
shortsDraftBaseline = null;
}
async function saveShorts() {
@@ -495,7 +593,7 @@ async function saveShorts() {
showToast(err.error || 'Ошибка');
return;
}
closeModal();
closeModal(false);
shortsPage = 1;
await loadShorts();
showToast(editingId ? 'Сообщение обновлено' : 'Сообщения добавлены');
@@ -629,6 +727,7 @@ function acceptShortsAi() {
if (suggestion && suggestion !== 'Обработка...' && !suggestion.startsWith('Ошибка:')) {
document.getElementById('shortsLines').value = suggestion;
updateShortsLinesCount();
scheduleShortsDraft();
}
closeShortsAi();
}
+1
View File
@@ -147,6 +147,7 @@
<input type="date" id="shortsUsedAt" class="settings-input">
</div>
<div class="card-foot" style="justify-content:flex-end;border-top:none;padding-top:0">
<span class="field-note" style="margin-right:auto">Поля сохраняются автоматически</span>
<button type="button" class="btn-primary ghost" id="shortsCancel">Отмена</button>
<button type="button" class="btn-primary" id="shortsSave">Сохранить</button>
</div>