docs: вложения статей (doc_files), подписи и библиотека картинок, быстрое ред. отзыва

This commit is contained in:
dev
2026-11-01 11:06:23 +03:00
parent a6f5953c61
commit 9a509fa742
12 changed files with 947 additions and 25 deletions
+326 -1
View File
@@ -13,6 +13,11 @@
const hintEl = el('docsEditHint');
const searchEl = el('docsSearch');
const imageFileEl = el('docsImageFile');
const fileInputEl = el('docsFileInput');
const filesBodyEl = el('docsFilesBody');
const filesPanelEl = el('docsFilesPanel');
const imgLibModal = el('docsImageLibModal');
const imgLibGrid = el('docsImgLibGrid');
const sectionModal = el('docsSectionModal');
const sectionTitleEl = el('docsSectionTitle');
const sectionParentEl = el('docsSectionParent');
@@ -182,6 +187,10 @@
<div class="docs-meta">${meta.join('')}</div>
<div class="docs-article-actions">${actions.join('')}</div>
<div class="docs-body">${WhatIDoMD.render(article.body)}</div>
${(article.files && article.files.length) ? `<div class="docs-attachments">
<div class="docs-attachments-title">Вложения</div>
<ul class="docs-attachments-list">${article.files.map(f => `<li><a href="${esc(f.path)}" target="_blank" rel="noopener">${esc(f.name)}</a> <span class="docs-attach-size">${fmtBytes(f.size_bytes)}</span></li>`).join('')}</ul>
</div>` : ''}
</article>`;
}
@@ -203,6 +212,10 @@
if (editState && editState.dirty && !confirm('Несохранённые изменения будут потеряны. Продолжить?')) return;
const data = await req('/api/docs/articles/' + encodeURIComponent(slug));
current = data.item;
try {
const fdata = await req('/api/docs/articles/' + current.id + '/files');
current.files = fdata.items || [];
} catch (e) { current.files = []; }
editState = null;
if (updateHash !== false) history.replaceState(null, '', '#a=' + encodeURIComponent(current.slug));
renderArticle();
@@ -246,7 +259,8 @@
showToast('Нет разделов, где вам разрешено писать', true);
return;
}
editState = { id: article ? article.id : null, dirty: false };
editState = { id: article ? article.id : null, dirty: false, files: [] };
if (article && article.id) loadDocFiles(article.id); else renderDocFilesTable();
titleEl.value = article ? article.title : '';
bodyEl.value = article ? article.body : '';
publishedEl.checked = article ? article.is_published : true;
@@ -290,6 +304,7 @@
is_public: isAdmin() ? publicEl.checked : false,
};
const saveBtn = el('docsSaveBtn');
const pendingFileIds = (editState && editState.files ? editState.files : []).filter(f => !f.article_id).map(f => f.id);
saveBtn.disabled = true;
try {
const path = editState.id ? '/api/docs/articles/' + editState.id : '/api/docs/articles';
@@ -297,6 +312,9 @@
const data = await req(path, { method, body: JSON.stringify(payload) });
editState.dirty = false;
closeEditor();
for (const fid of pendingFileIds) {
try { await req('/api/docs/files/' + fid + '/attach', { method: 'PUT', body: JSON.stringify({ article_id: data.item.id }) }); } catch (e) {}
}
await loadTree();
await openArticle(data.item.slug);
showToast('Статья сохранена');
@@ -401,6 +419,223 @@
}
}
function fmtBytes(n) {
n = Number(n) || 0;
if (n < 1024) return n + ' Б';
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' КБ';
return (n / (1024 * 1024)).toFixed(1) + ' МБ';
}
async function loadDocFiles(articleId) {
if (!editState) return;
if (!articleId) {
// unsaved article: show unattached files + unattached images
try {
const [fdata, idata] = await Promise.all([
req('/api/docs/files/unattached'),
req('/api/docs/images/unattached'),
]);
const files = (fdata.items || []).map(x => Object.assign({}, x, { _kind: 'file', _unattached: true }));
const images = (idata.items || []).map(x => Object.assign({}, x, { _kind: 'image', name: (x.path || '').split('/').pop(), size_bytes: null, mime: 'image/*', _unattached: true }));
editState.files = files.concat(images);
renderDocFilesTable();
} catch (e) {
editState.files = [];
renderDocFilesTable();
}
return;
}
try {
const [fdata, idata] = await Promise.all([
req('/api/docs/articles/' + articleId + '/files'),
req('/api/docs/articles/' + articleId + '/images'),
]);
const files = (fdata.items || []).map(x => Object.assign({}, x, { _kind: 'file' }));
const images = (idata.items || []).map(x => Object.assign({}, x, { _kind: 'image', name: (x.path || '').split('/').pop(), size_bytes: null, mime: 'image/*' }));
editState.files = files.concat(images);
renderDocFilesTable();
} catch (e) {
editState.files = [];
renderDocFilesTable();
}
}
function docFileStatus(f) {
const body = bodyEl.value || '';
const used = body.indexOf(f.path) !== -1;
if (used) return '<span class="docs-badge">В тексте</span>';
if (f.article_id) return '<span class="docs-badge">Прикреплён</span>';
return '<span class="docs-badge">Не привязан</span>';
}
function renderDocFilesTable() {
if (!filesBodyEl) return;
const files = (editState && editState.files) || [];
if (!files.length) {
filesBodyEl.innerHTML = '<tr><td colspan="4" class="docs-empty" style="padding:8px">Вложений пока нет</td></tr>';
return;
}
filesBodyEl.innerHTML = files.map(f => {
const isImg = f._kind === 'image';
const thumb = isImg ? `<img src="/uploads/thumb/${esc(f.path.split('/').pop())}" alt="" style="width:36px;height:36px;object-fit:cover;border-radius:6px;vertical-align:middle;margin-right:6px">` : '';
const acts = f._unattached
? (isImg
? `<button type="button" class="btn-primary ghost" data-file-act="delete" style="color:#ef4444;border-color:rgba(239,68,68,.35)" title="Удалить">Удалить</button>`
: `<button type="button" class="btn-primary ghost" data-file-act="attach" title="Прикрепить к статье">Прикрепить</button>
<button type="button" class="btn-primary ghost" data-file-act="delete" style="color:#ef4444;border-color:rgba(239,68,68,.35)" title="Удалить">Удалить</button>`)
: (isImg
? `<button type="button" class="btn-primary ghost" data-file-act="insert" title="Вставить в текст">Вставить</button>
<button type="button" class="btn-primary ghost" data-file-act="delete" style="color:#ef4444;border-color:rgba(239,68,68,.35)" title="Удалить">Удалить</button>`
: `<button type="button" class="btn-primary ghost" data-file-act="insert" title="Вставить в текст">Вставить</button>
<button type="button" class="btn-primary ghost" data-file-act="replace" title="Заменить файл">Заменить</button>
<button type="button" class="btn-primary ghost" data-file-act="detach" title="Открепить">Открепить</button>
<button type="button" class="btn-primary ghost" data-file-act="delete" style="color:#ef4444;border-color:rgba(239,68,68,.35)" title="Удалить">Удалить</button>`);
const status = isImg ? '<span class="docs-badge">Картинка</span>' : (f._unattached ? '<span class="docs-badge">Не привязан</span>' : docFileStatus(f));
const captionInput = isImg ? `<div class="docs-caption-row"><input class="docs-caption-input" data-caption-for="${f.id}" value="${esc(f.caption || '')}" placeholder="Подпись (alt/title)" maxlength="300"><button type="button" class="btn-primary ghost" data-file-act="caption" title="Сохранить подпись">✓</button></div>` : '';
return `<tr data-file-id="${f.id}" data-file-kind="${f._kind || 'file'}">
<td>${thumb}<a href="${esc(f.path)}" target="_blank" rel="noopener">${esc(f.name)}</a>${captionInput}</td>
<td>${isImg ? '—' : fmtBytes(f.size_bytes)}</td>
<td>${status}</td>
<td class="docs-files-acts">${acts}</td>
</tr>`;
}).join('');
}
async function uploadDocFile(file, articleId) {
if (!file) return;
showToast('Загрузка файла...');
try {
const form = new FormData();
form.append('file', file);
if (articleId) form.append('article_id', String(articleId));
const data = await req('/api/docs/files', { method: 'POST', body: form });
if (editState) {
editState.files = editState.files || [];
editState.files.unshift(data.item);
renderDocFilesTable();
}
showToast('Файл прикреплён');
} catch (e) {
showToast(e.message, true);
}
}
async function replaceDocFile(id) {
const input = document.createElement('input');
input.type = 'file';
input.onchange = async () => {
const file = input.files && input.files[0];
if (!file) return;
showToast('Замена файла...');
try {
const form = new FormData();
form.append('file', file);
const data = await req('/api/docs/files/' + id + '/replace', { method: 'POST', body: form });
const old = (editState.files || []).find(f => Number(f.id) === Number(id));
if (old && old.path && data.item.path && bodyEl.value.indexOf(old.path) !== -1) {
bodyEl.value = bodyEl.value.split(old.path).join(data.item.path);
markDirty();
updatePreview();
}
if (editState) {
editState.files = (editState.files || []).map(f => Number(f.id) === Number(id) ? data.item : f);
renderDocFilesTable();
}
showToast('Файл заменён');
} catch (e) {
showToast(e.message, true);
}
};
input.click();
}
async function detachDocFile(id) {
if (!confirm('Открепить файл от статьи?')) return;
try {
const data = await req('/api/docs/files/' + id + '/attach', { method: 'PUT', body: JSON.stringify({ article_id: null }) });
if (editState) {
editState.files = (editState.files || []).filter(f => Number(f.id) !== Number(id));
renderDocFilesTable();
}
showToast('Файл откреплён');
} catch (e) {
showToast(e.message, true);
}
}
async function deleteDocFile(id) {
if (!confirm('Удалить файл без возможности восстановления?')) return;
try {
await req('/api/docs/files/' + id, { method: 'DELETE' });
if (editState) {
editState.files = (editState.files || []).filter(f => Number(f.id) !== Number(id));
renderDocFilesTable();
}
showToast('Файл удалён');
} catch (e) {
showToast(e.message, true);
}
}
function isImageFile(f) {
const mime = String(f.mime || '').toLowerCase();
if (mime.startsWith('image/')) return true;
return /\.(jpe?g|png|gif|webp|bmp|avif|ico|jfif)$/i.test(String(f.name || f.path || ''));
}
function insertDocFileLink(f) {
const md = isImageFile(f) ? `![${f.name}](${f.path})` : `[${f.name}](${f.path})`;
insertBlock(md);
}
async function loadUnattachedDocFiles() {
try {
const data = await req('/api/docs/files/unattached');
const items = data.items || [];
if (!items.length) { showToast('Нет незагруженных файлов', true); return; }
const prev = (editState && editState.files) || [];
const merged = prev.concat(items.map(x => Object.assign({}, x, { _unattached: true })));
if (editState) { editState.files = merged; renderDocFilesTable(); }
} catch (e) {
showToast(e.message, true);
}
}
async function openImageLibrary() {
if (!imgLibModal || !imgLibGrid) return;
imgLibGrid.innerHTML = '<div class="docs-empty">Загрузка...</div>';
imgLibModal.classList.add('open');
try {
const data = await req('/api/docs/images');
const items = data.items || [];
if (!items.length) {
imgLibGrid.innerHTML = '<div class="docs-empty">Изображений пока нет</div>';
return;
}
imgLibGrid.innerHTML = items.map(it => `
<div class="docs-imglib-item" data-img-path="${esc(it.path)}" title="${esc(it.path)}">
<img src="${esc('/uploads/thumb/' + it.path.split('/').pop())}" alt="" loading="lazy">
<div class="docs-imglib-name">${esc(it.path.split('/').pop())}</div>
</div>`).join('');
} catch (e) {
imgLibGrid.innerHTML = '<div class="docs-empty">' + esc(e.message) + '</div>';
}
}
async function loadAllDocFiles() {
try {
const data = await req('/api/docs/files');
const items = (data.items || []).map(x => Object.assign({}, x, { _all: true }));
if (editState) {
// mark which are attached to current article
const curId = editState.id;
editState.files = items.map(x => Object.assign({}, x, { _unattached: !x.article_id || Number(x.article_id) !== Number(curId) }));
renderDocFilesTable();
}
} catch (e) {
showToast(e.message, true);
}
}
function fillParentSelect(excludeId, selectedId) {
const list = sectionList().filter(s => Number(s.id) !== Number(excludeId));
sectionParentEl.innerHTML = '<option value="">— Корень —</option>' + list.map(s => {
@@ -623,6 +858,96 @@
imageFileEl.value = '';
if (file) await uploadImage(file);
});
if (fileInputEl) fileInputEl.addEventListener('change', async () => {
const files = [...(fileInputEl.files || [])];
fileInputEl.value = '';
const aid = editState && editState.id ? editState.id : null;
for (const f of files) await uploadDocFile(f, aid);
if (aid) await loadDocFiles(aid);
});
const uploadBtn = el('docsFileUploadBtn');
if (uploadBtn) uploadBtn.addEventListener('click', () => fileInputEl && fileInputEl.click());
const pickerBtn = el('docsFilePickerBtn');
if (pickerBtn) pickerBtn.addEventListener('click', async () => {
if (!editState || !editState.id) { showToast('Сначала сохраните статью', true); return; }
await loadUnattachedDocFiles();
});
const allBtn = el('docsFileAllBtn');
if (allBtn) allBtn.addEventListener('click', async () => {
if (!editState || !editState.id) { showToast('Сначала сохраните статью', true); return; }
await loadAllDocFiles();
});
const libBtn = el('docsImgLibBtn');
if (libBtn) libBtn.addEventListener('click', () => openImageLibrary());
const libClose = el('docsImgLibClose');
if (libClose) libClose.addEventListener('click', () => imgLibModal && imgLibModal.classList.remove('open'));
if (imgLibModal) imgLibModal.addEventListener('click', e => { if (e.target === imgLibModal) imgLibModal.classList.remove('open'); });
if (imgLibGrid) imgLibGrid.addEventListener('click', e => {
const item = e.target.closest('.docs-imglib-item');
if (!item) return;
const p = item.dataset.imgPath;
if (!p) return;
const name = p.split('/').pop().replace(/\.[^.]+$/, '');
insertBlock(`![${name}](${p})`);
if (imgLibModal) imgLibModal.classList.remove('open');
showToast('Картинка вставлена');
});
if (filesBodyEl) filesBodyEl.addEventListener('click', e => {
const btn = e.target.closest('[data-file-act]');
if (!btn) return;
const tr = btn.closest('tr');
const id = tr && tr.dataset.fileId;
if (!id) return;
const act = btn.dataset.fileAct;
const f = (editState.files || []).find(x => String(x.id) === String(id));
if (act === 'insert' && f) insertDocFileLink(f);
if (act === 'caption') {
const input = tr.querySelector('.docs-caption-input');
const val = input ? input.value : '';
req('/api/docs/images/' + id, { method: 'PUT', body: JSON.stringify({ caption: val }) })
.then(data => {
if (editState) {
editState.files = (editState.files || []).map(x => String(x.id) === String(id) && x._kind === 'image' ? Object.assign({}, x, { caption: data.item.caption }) : x);
renderDocFilesTable();
}
if (data.item.body && editState) {
bodyEl.value = data.item.body;
markDirty();
updatePreview();
}
showToast('Подпись сохранена');
}).catch(err => showToast(err.message, true));
return;
}
if (act === 'replace') replaceDocFile(id);
if (act === 'detach') detachDocFile(id);
if (act === 'delete') {
const kind = tr.dataset.fileKind || (f && f._kind) || 'file';
if (kind === 'image') {
req('/api/docs/images/' + id, { method: 'DELETE' })
.then(() => {
if (editState) {
editState.files = (editState.files || []).filter(x => !(String(x.id) === String(id) && x._kind === 'image'));
renderDocFilesTable();
}
showToast('Изображение удалено');
}).catch(err => showToast(err.message, true));
} else {
deleteDocFile(id);
}
}
if (act === 'attach') {
if (!editState || !editState.id) { showToast('Сначала сохраните статью', true); return; }
req('/api/docs/files/' + id + '/attach', { method: 'PUT', body: JSON.stringify({ article_id: editState.id }) })
.then(data => {
if (editState) {
editState.files = (editState.files || []).map(x => String(x.id) === String(id) ? data.item : x).filter(x => x.article_id);
renderDocFilesTable();
}
showToast('Файл прикреплён');
}).catch(err => showToast(err.message, true));
}
});
el('docsSaveBtn').addEventListener('click', saveArticle);
el('docsCancelBtn').addEventListener('click', cancelEdit);
}