(async function() {
'use strict';
let digests = [];
let editingId = null;
let saving = false;
let previewPath = null;
let previewRemoved = false;
let previewFile = null;
let digestImages = [];
const DRAFT_KEY = 'whatido:digest:draft';
function draftPayload() {
const titleEl = document.getElementById('digestTitle');
const bodyEl = document.getElementById('digestBody');
const pinnedEl = document.getElementById('digestPinned');
const postAtEl = document.getElementById('digestPostAt');
const hideAtEl = document.getElementById('digestHideAt');
return {
title: titleEl ? titleEl.value : '',
body: bodyEl ? bodyEl.value : '',
isPinned: pinnedEl ? pinnedEl.checked : false,
postAt: postAtEl ? postAtEl.value : '',
hideAt: hideAtEl ? hideAtEl.value : '',
previewPath: previewPath || null
};
}
function persistDraft() {
try { localStorage.setItem(DRAFT_KEY, JSON.stringify(draftPayload())); } catch (e) {}
}
function restoreDraft() {
try {
const raw = localStorage.getItem(DRAFT_KEY);
if (!raw) return;
const d = JSON.parse(raw);
if (!d || typeof d !== 'object') return;
const titleEl = document.getElementById('digestTitle');
const bodyEl = document.getElementById('digestBody');
const pinnedEl = document.getElementById('digestPinned');
const postAtEl = document.getElementById('digestPostAt');
const hideAtEl = document.getElementById('digestHideAt');
if (titleEl && d.title != null) titleEl.value = d.title;
if (bodyEl && d.body != null) bodyEl.value = d.body;
if (pinnedEl && d.isPinned != null) pinnedEl.checked = !!d.isPinned;
if (postAtEl && d.postAt != null) postAtEl.value = d.postAt;
if (hideAtEl && d.hideAt != null) hideAtEl.value = d.hideAt;
previewPath = d.previewPath || null;
showPreview(previewPath);
} catch (e) {}
}
function clearDraft() {
try { localStorage.removeItem(DRAFT_KEY); } catch (e) {}
}
function hasDraft() {
try {
const raw = localStorage.getItem(DRAFT_KEY);
if (!raw) return false;
const d = JSON.parse(raw);
return Boolean(d && (d.title || d.body || d.postAt || d.hideAt || d.previewPath || d.isPinned));
} catch { return false; }
}
function esc(s) {
return String(s || '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
function escAttr(s) {
const d = document.createElement('textarea');
d.textContent = s || '';
return d.value;
}
function tzOffsetMinutes(instant) {
try {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: DateTime.tz, hour12: false, timeZoneName: 'shortOffset'
}).formatToParts(new Date(instant));
const m = /([+-])(\d{2}):(\d{2})/.exec(parts.find(p => p.type === 'timeZoneName')?.value || '');
if (!m) return 0;
return (m[1] === '+' ? 1 : -1) * (Number(m[2]) * 60 + Number(m[3]));
} catch { return 0; }
}
function toLocalInput(iso) {
if (!iso) return '';
try {
const d = new Date(iso);
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: DateTime.tz, year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', hour12: false
}).formatToParts(d);
const get = name => parts.find(p => p.type === name)?.value || '';
return `${get('year')}-${get('month')}-${get('day')}T${get('hour')}:${get('minute')}`;
} catch { return ''; }
}
function inputToIso(localDt) {
if (!localDt) return null;
try {
const [datePart, timePart] = String(localDt).split('T');
const [y, mo, d] = datePart.split('-').map(Number);
const [h, mi] = timePart.split(':').map(Number);
const ref = new Date(Date.UTC(y, mo - 1, d, h, mi, 0, 0));
const off = tzOffsetMinutes(ref);
return new Date(ref.getTime() - off * 60000).toISOString();
} catch { return null; }
}
function thumbSrc(p) {
if (!p) return '';
if (p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`;
return p;
}
function fmtDigestDate(iso) {
if (!iso) return '—';
try {
return new Intl.DateTimeFormat('ru-RU', {
timeZone: DateTime.tz, day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit'
}).format(new Date(iso));
} catch { return String(iso).slice(0, 16); }
}
function digestCardHtml(d) {
const admin = isAdmin();
const mine = currentUser && d.author_id === currentUser.id;
const canEdit = admin || mine;
const pinned = !!d.is_pinned;
const nowTs = new Date();
const hidden = d.hide_at && new Date(d.hide_at) <= nowTs;
const badge = [];
if (pinned) badge.push('Закреплено');
if (d.post_at) badge.push('Публикация ' + fmtDigestDate(d.post_at) + '');
if (d.hide_at) badge.push('Скрыть ' + fmtDigestDate(d.hide_at) + '');
const preview = d.preview_path
? '
) + ')
'
: '';
const images = Array.isArray(d.images) ? d.images : [];
let imagesHtml = '';
if (images.length) {
imagesHtml = '' + images.slice(0, 4).map(function(img) {
return '
) + ')
';
}).join('') + (images.length > 4 ? '
+ ' + (images.length - 4) + '' : '') + '
';
}
const actions = [];
if (canEdit) {
actions.push('');
actions.push('');
}
if (admin) {
actions.push('');
}
return '' +
'
' +
'
' + esc(d.title) + '
' +
badge.join('') +
'' +
preview +
'
' +
'' + esc(d.author_name || '—') + '' +
'' + fmtShortIso(d.created_at) + '' +
'
' +
'
' + esc(d.body) + '
' +
imagesHtml +
'' +
'
';
}
function renderDigests() {
const el = document.getElementById('digestList');
if (!el) return;
if (!digests.length) {
el.innerHTML = 'Сообщений пока нет
';
return;
}
el.innerHTML = digests.map(digestCardHtml).join('');
renderIcons();
}
async function loadDigests() {
let res;
try {
res = await fetch(API + '/api/digests', { headers: hdr() });
} catch (e) {
showToast('Ошибка сети при загрузке дайджеста', true);
return;
}
if (!res.ok) return;
const data = await res.json().catch(function() { return {}; });
digests = Array.isArray(data.items) ? data.items : (Array.isArray(data) ? data : []);
renderDigests();
}
async function loadImages(digestId) {
let res;
try {
res = await fetch(API + '/api/digests/' + digestId + '/images', { headers: hdr() });
} catch (e) {
showToast('Ошибка сети при загрузке вложений', true);
return [];
}
if (!res.ok) return [];
const data = await res.json().catch(function() { return {}; });
digestImages = Array.isArray(data.items) ? data.items : [];
renderImageGallery();
return digestImages;
}
function renderImageGallery() {
const wrap = document.getElementById('digestImagesWrap');
if (!wrap) return;
if (!digestImages.length) {
wrap.innerHTML = 'Ещё нет картинок';
return;
}
wrap.innerHTML = digestImages.map(function(img) {
return '' +
'
) + ')
' +
'
' +
'
';
}).join('');
}
function showPreview(path) {
const img = document.getElementById('digestPreviewImg');
const wrap = document.getElementById('digestPreviewWrap');
const btn = document.getElementById('digestPreviewRemove');
if (path) {
img.src = thumbSrc(path);
img.style.display = 'block';
previewPath = path;
} else {
img.src = '';
img.style.display = 'none';
previewPath = null;
}
btn.style.display = path || previewRemoved || previewFile ? '' : 'none';
}
function openDigestModal(d) {
editingId = d ? d.id : null;
previewPath = d ? d.preview_path : null;
previewRemoved = false;
previewFile = null;
digestImages = [];
document.getElementById('digestModalTitle').textContent = d ? 'Редактирование сообщения' : 'Новое сообщение';
document.getElementById('digestTitle').value = d ? escAttr(d.title) : '';
document.getElementById('digestBody').value = d ? escAttr(d.body) : '';
document.getElementById('digestPostAt').value = d ? toLocalInput(d.post_at) : '';
document.getElementById('digestHideAt').value = d ? toLocalInput(d.hide_at) : '';
const pinRow = document.getElementById('digestPinned').closest('.settings-field');
const pinInput = document.getElementById('digestPinned');
pinInput.checked = d ? !!d.is_pinned : false;
pinRow.style.display = isAdmin() ? '' : 'none';
showPreview(d ? d.preview_path : null);
document.getElementById('digestImageFile').value = '';
const canManageImages = !!editingId;
document.getElementById('digestImageAdd').style.display = canManageImages ? '' : 'none';
document.getElementById('digestImagesWrap').style.display = canManageImages ? '' : 'none';
if (canManageImages) {
loadImages(editingId);
} else {
document.getElementById('digestImagesWrap').innerHTML = 'Сохраните сообщение, чтобы добавить картинки';
}
if (editingId) {
clearDraft();
} else {
restoreDraft();
}
document.getElementById('digestModal').classList.add('open');
document.getElementById('digestTitle').focus();
}
function closeDigestModal() {
if (hasDraft() && !confirm('Есть несохранённые изменения. Закрыть без сохранения?')) return;
document.getElementById('digestModal').classList.remove('open');
editingId = null;
previewPath = null;
previewRemoved = false;
previewFile = null;
digestImages = [];
clearDraft();
}
async function uploadPreview(digestId) {
if (!previewFile) return;
if (previewRemoved) {
try {
await fetch(API + '/api/digests/' + digestId + '/preview', { method: 'DELETE', headers: hdr() });
} catch (e) { console.error('preview clear:', e); }
previewRemoved = false;
return;
}
const fd = new FormData();
fd.append('image', previewFile);
try {
const res = await fetch(API + '/api/digests/' + digestId + '/preview', {
method: 'POST', headers: hdr(), body: fd
});
if (!res.ok) {
const data = await res.json().catch(function() { return {}; });
showToast(data.error || 'Не удалось загрузить превью', true);
}
} catch (e) {
showToast('Ошибка сети при загрузке превью', true);
}
}
async function doSaveDigest() {
const title = document.getElementById('digestTitle').value.trim();
const body = document.getElementById('digestBody').value.trim();
const isPinned = document.getElementById('digestPinned').checked;
const postAt = inputToIso(document.getElementById('digestPostAt').value);
const hideAt = inputToIso(document.getElementById('digestHideAt').value);
if (!title) { showToast('Введите заголовок', true); return null; }
if (!body) { showToast('Введите текст сообщения', true); return null; }
if (saving) return null;
const payload = { title: title, body: body, is_pinned: isPinned, preview_path: previewPath || null, post_at: postAt, hide_at: hideAt };
saving = true;
let res;
try {
if (editingId) {
res = await fetch(API + '/api/digests/' + editingId, {
method: 'PUT', headers: hdrJson(), body: JSON.stringify(payload)
});
} else {
res = await fetch(API + '/api/digests', { method: 'POST', headers: hdrJson(), body: JSON.stringify(payload) });
}
} catch (e) {
saving = false;
showToast('Ошибка сети', true);
return null;
}
const data = await res.json().catch(function() { return {}; });
saving = false;
if (!res.ok) {
showToast(data.error || 'Ошибка при сохранении', true);
return null;
}
const savedId = editingId || (data.item && data.item.id);
if (savedId) {
await uploadPreview(savedId);
previewFile = null;
}
return savedId;
}
async function saveDigest() {
const savedId = await doSaveDigest();
if (savedId === null) return;
if (!editingId) {
showToast('Сообщение создано');
clearDraft();
closeDigestModal();
await loadDigests();
return;
}
showToast('Сообщение обновлено');
clearDraft();
closeDigestModal();
await loadDigests();
}
async function digestPaste(e) {
const m = document.getElementById('digestModal');
if (!m || !m.classList.contains('open')) return;
const active = document.activeElement;
if (!active || active.id !== 'digestBody') return;
const clip = e.clipboardData;
if (!clip) return;
const pasted = [];
for (const item of Array.from(clip.items || [])) {
if (item.kind !== 'file') continue;
const file = item.getAsFile();
if (file && /^image\//i.test(file.type || '')) pasted.push(file);
}
if (!pasted.length && clip.files && clip.files.length) {
for (const f of Array.from(clip.files)) {
if (/^image\//i.test(f.type || '')) pasted.push(f);
}
}
if (!pasted.length) return;
e.preventDefault();
let targetId = editingId;
if (!targetId) {
const saved = await doSaveDigest();
if (!saved) return;
targetId = saved;
editingId = targetId;
document.getElementById('digestImageAdd').style.display = '';
document.getElementById('digestImagesWrap').style.display = '';
}
let pending = pasted.length, failed = 0;
for (const file of pasted) {
const fd = new FormData();
fd.append('image', file);
try {
const res = await fetch(API + '/api/digests/' + targetId + '/images', {
method: 'POST', headers: hdr(), body: fd
});
if (!res.ok) { failed++; continue; }
const data = await res.json().catch(function() { return {}; });
if (data.item) digestImages.push(data.item);
} catch (err) { failed++; }
}
renderImageGallery();
await loadDigests();
if (pending) {
const ok = pending - failed;
if (failed) showToast('Вставлено ' + ok + ' из ' + pending + ' картинок', true);
else showToast('Картинок вставлено: ' + ok);
}
}
async function addPreviewFile() {
const input = document.getElementById('digestPreviewFile');
if (!input.files || !input.files.length) return;
previewFile = input.files[0];
previewRemoved = false;
const url = URL.createObjectURL(previewFile);
const img = document.getElementById('digestPreviewImg');
img.src = url;
img.style.display = 'block';
document.getElementById('digestPreviewRemove').style.display = '';
input.value = '';
showToast('Превью выбрано, загрузится при сохранении');
}
async function removePreview() {
previewRemoved = true;
previewFile = null;
document.getElementById('digestPreviewImg').src = '';
document.getElementById('digestPreviewImg').style.display = 'none';
document.getElementById('digestPreviewRemove').style.display = 'none';
previewPath = null;
}
async function addImages() {
if (!editingId) { showToast('Сначала сохраните сообщение', true); return; }
const input = document.getElementById('digestImageFile');
if (!input.files || !input.files.length) return;
const files = Array.from(input.files);
let pending = files.length;
let failed = 0;
input.value = '';
for (const file of files) {
const fd = new FormData();
fd.append('image', file);
try {
const res = await fetch(API + '/api/digests/' + editingId + '/images', {
method: 'POST', headers: hdr(), body: fd
});
if (!res.ok) {
failed++;
continue;
}
const data = await res.json().catch(function() { return {}; });
if (data.item) digestImages.push(data.item);
} catch (e) {
failed++;
}
}
if (pending) {
renderImageGallery();
await loadDigests();
if (failed) showToast('Загружено ' + (pending - failed) + ' из ' + pending + ' картинок', true);
else showToast('Картинки добавлены');
}
}
async function removeImage(imageId) {
if (!confirm('Удалить картинку из сообщения и с диска?')) return;
let res;
try {
res = await fetch(API + '/api/digests/images/' + imageId, { method: 'DELETE', headers: hdr() });
} catch (e) {
showToast('Ошибка сети', true);
return;
}
if (!res.ok) {
const data = await res.json().catch(function() { return {}; });
showToast(data.error || 'Не удалось удалить картинку', true);
return;
}
digestImages = digestImages.filter(function(img) { return img.id !== imageId; });
renderImageGallery();
await loadDigests();
showToast('Картинка удалена');
}
async function togglePin(id, toPin) {
let res;
try {
res = await fetch(API + '/api/digests/' + id + '/pin', { method: 'PUT', headers: hdr() });
} catch (e) {
showToast('Ошибка сети', true);
return;
}
const data = await res.json().catch(function() { return {}; });
if (!res.ok) {
showToast(data.error || 'Ошибка', true);
return;
}
await loadDigests();
showToast(toPin ? 'Закреплено' : 'Откреплено');
}
async function removeDigest(id) {
if (!confirm('Удалить это сообщение из дайджеста?')) return;
let res;
try {
res = await fetch(API + '/api/digests/' + id, { method: 'DELETE', headers: hdr() });
} catch (e) {
showToast('Ошибка сети', true);
return;
}
if (!res.ok) {
const data = await res.json().catch(function() { return {}; });
showToast(data.error || 'Ошибка при удалении', true);
return;
}
digests = digests.filter(function(d) { return d.id !== id; });
renderDigests();
showToast('Сообщение удалено');
}
function bindModal() {
document.getElementById('digestModalClose').addEventListener('click', closeDigestModal);
document.getElementById('digestCancel').addEventListener('click', closeDigestModal);
document.getElementById('digestSave').addEventListener('click', saveDigest);
document.getElementById('digestPreviewFile').addEventListener('change', addPreviewFile);
document.getElementById('digestPreviewRemove').addEventListener('click', removePreview);
document.getElementById('digestImageAdd').addEventListener('click', addImages);
document.getElementById('digestImageFile').addEventListener('change', addImages);
document.getElementById('digestBody').addEventListener('paste', digestPaste);
const draftTitle = document.getElementById('digestTitle');
const draftBody = document.getElementById('digestBody');
const draftPinned = document.getElementById('digestPinned');
const draftPostAt = document.getElementById('digestPostAt');
const draftHideAt = document.getElementById('digestHideAt');
[draftTitle, draftBody].forEach(el => el && el.addEventListener('input', persistDraft));
[draftPinned, draftPostAt, draftHideAt].forEach(el => el && el.addEventListener('change', persistDraft));
document.getElementById('digestImagesWrap').addEventListener('click', function(e) {
const btn = e.target.closest('[data-action="del-image"]');
if (btn) removeImage(parseInt(btn.dataset.id, 10));
});
document.getElementById('digestModal').addEventListener('click', function(e) {
if (e.target === e.currentTarget) closeDigestModal();
});
document.addEventListener('keydown', function(e) {
const m = document.getElementById('digestModal');
const open = m && m.classList.contains('open');
if (e.key === 'Escape' && open) closeDigestModal();
});
}
function bindPage() {
document.getElementById('digestNewBtn').addEventListener('click', function() { openDigestModal(null); });
document.addEventListener('click', async function(e) {
const actEl = e.target.closest('[data-action]');
if (actEl) {
const action = actEl.dataset.action;
const id = parseInt(actEl.dataset.id, 10);
if (action === 'edit') {
const d = digests.find(function(x) { return x.id === id; });
if (d) openDigestModal(d);
return;
}
if (action === 'delete') { await removeDigest(id); return; }
if (action === 'pin') { await togglePin(id, actEl.dataset.pin === '1'); return; }
return;
}
});
}
async function init() {
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
const nb = document.getElementById('digestNewBtn');
if (nb) nb.style.display = isAdmin() ? '' : 'none';
bindModal();
bindPage();
renderIcons();
await loadDigests();
}
init();
})();