Files

1203 lines
50 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function () {
const el = id => document.getElementById(id);
const treeEl = el('docsTree');
const contentEl = el('docsContent');
const editorEl = el('docsEditor');
const titleEl = el('docsEditTitle');
const sectionEl = el('docsEditSection');
const publishedEl = el('docsEditPublished');
const publicEl = el('docsEditPublic');
const publicWrap = el('docsEditPublicWrap');
const bodyEl = el('docsEditBody');
const previewEl = el('docsPreview');
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');
const sectionTutorEl = el('docsSectionTutor');
const sectionPublicEl = el('docsSectionPublic');
const sectionDeleteBtn = el('docsSectionDeleteBtn');
const COLLAPSE_KEY = 'whatido.docs.collapsed';
let tree = [];
let current = null;
let editState = null;
let sectionEditId = null;
let collapsed = new Set();
let searchTimer = null;
let previewTimer = null;
const IMAGE_EXT_RE = /\.(jpe?g|png|gif|webp|bmp|avif|ico|heic|heif|jfif)$/i;
try {
const saved = JSON.parse(localStorage.getItem(COLLAPSE_KEY) || '[]');
if (Array.isArray(saved)) collapsed = new Set(saved.map(Number));
} catch (e) {}
async function req(path, options) {
const opts = options || {};
const headers = opts.body instanceof FormData ? hdr() : hdrJson();
const res = await fetch(API + path, Object.assign({}, opts, { headers }));
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка запроса');
return data;
}
function saveCollapsed() {
localStorage.setItem(COLLAPSE_KEY, JSON.stringify([...collapsed]));
}
function sectionList() {
const out = [];
const walk = (nodes, depth) => {
for (const node of nodes) {
out.push(Object.assign({}, node, { depth }));
walk(node.children || [], depth + 1);
}
};
walk(tree, 0);
return out;
}
function findSection(id) {
return sectionList().find(s => Number(s.id) === Number(id)) || null;
}
function findSectionNode(id) {
let found = null;
const walk = nodes => {
for (const node of nodes) {
if (Number(node.id) === Number(id)) { found = node; return; }
walk(node.children || []);
if (found) return;
}
};
walk(tree);
return found;
}
function canCreateAnywhere() {
return isAdmin() || sectionList().some(s => s.can_write);
}
function updateNewArticleButton() {
const btn = el('docsNewArticleBtn');
if (btn) btn.hidden = !canCreateAnywhere();
}
async function loadTree() {
const data = await req('/api/docs/tree');
tree = data.sections || [];
updateNewArticleButton();
if (searchEl.value.trim().length >= 2) {
renderTree();
runSearch();
} else {
renderTree();
}
}
function renderIconsSafe() {
if (typeof renderIcons === 'function') renderIcons();
}
function sectionActs(node) {
const acts = [];
if (node.can_write) acts.push(`<button type="button" data-act="add-article" data-id="${node.id}" title="Новая статья"><i data-lucide="file-plus"></i></button>`);
if (isAdmin()) {
acts.push(`<button type="button" data-act="add-sub" data-id="${node.id}" title="Подраздел"><i data-lucide="folder-plus"></i></button>`);
acts.push(`<button type="button" data-act="edit-section" data-id="${node.id}" title="Изменить раздел"><i data-lucide="pencil"></i></button>`);
acts.push(`<button type="button" data-act="section-up" data-id="${node.id}" title="Выше"><i data-lucide="arrow-up"></i></button>`);
acts.push(`<button type="button" data-act="section-down" data-id="${node.id}" title="Ниже"><i data-lucide="arrow-down"></i></button>`);
}
return acts.join('');
}
function articleRow(article, depth) {
const active = current && Number(current.id) === Number(article.id);
const acts = isAdmin()
? `<button type="button" data-act="article-up" data-id="${article.id}" data-section="${article.section_id}" title="Выше"><i data-lucide="arrow-up"></i></button>
<button type="button" data-act="article-down" data-id="${article.id}" data-section="${article.section_id}" title="Ниже"><i data-lucide="arrow-down"></i></button>`
: '';
return `<div class="docs-article-row">
<a href="#a=${encodeURIComponent(article.slug)}" data-slug="${esc(article.slug)}" class="${active ? 'active' : ''}" style="padding-left:${26 + depth * 14}px" title="${esc(article.title)}">${esc(article.title)}${article.is_published ? '' : '<span class="docs-dot" title="Черновик"></span>'}</a>
<span class="docs-row-acts">${acts}</span>
</div>`;
}
function sectionNode(node, depth) {
const closed = collapsed.has(Number(node.id));
const hasItems = (node.children && node.children.length) || (node.articles && node.articles.length);
const chev = hasItems
? `<button type="button" class="docs-chev${closed ? ' closed' : ''}" data-toggle="${node.id}" aria-label="Свернуть раздел"><i data-lucide="chevron-down"></i></button>`
: '<span style="width:14px;flex:none"></span>';
const children = closed ? '' : [
...(node.children || []).map(child => sectionNode(child, depth + 1)),
...(node.articles || []).map(article => articleRow(article, depth + 1)),
].join('');
return `<div class="docs-node">
<div class="docs-section-row" data-section="${node.id}" style="padding-left:${8 + depth * 14}px">
${chev}
<i data-lucide="${closed ? 'folder' : 'folder-open'}"></i>
<span class="docs-section-title">${esc(node.title)}</span>
<span class="docs-row-acts">${sectionActs(node)}</span>
</div>
<div class="docs-children"${closed ? ' hidden' : ''}>${children}</div>
</div>`;
}
function renderTree() {
if (!tree.length) {
treeEl.innerHTML = '<div class="docs-empty">Разделов пока нет</div>';
renderIconsSafe();
return;
}
treeEl.innerHTML = tree.map(node => sectionNode(node, 0)).join('');
renderIconsSafe();
}
function renderEmpty() {
contentEl.hidden = false;
editorEl.hidden = true;
contentEl.innerHTML = `<div class="docs-article"><div class="docs-empty" style="padding:60px 16px">Выберите статью слева${canCreateAnywhere() ? ' или создайте новую' : ''}</div></div>`;
}
function articleHtml(article) {
const actions = [];
if (article.can_edit) {
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="edit" title="Редактировать"><i data-lucide="pencil"></i></button>');
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="delete" title="Удалить" style="color:#ef4444;border-color:rgba(239,68,68,.35)"><i data-lucide="trash-2"></i></button>');
}
if (article.is_public) {
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="copy" title="Скопировать публичную ссылку"><i data-lucide="link"></i></button>');
}
const meta = [];
if (article.author_name) meta.push(`<span>${esc(article.author_name)}</span>`);
if (article.updated_at) meta.push(`<span>Обновлено: ${fmtDateTime(article.updated_at)}</span>`);
if (!article.is_published) meta.push('<span class="docs-badge">Черновик</span>');
if (article.is_public) meta.push('<span class="docs-badge public">Публичная</span>');
return `<article class="docs-article">
<div class="docs-article-head">
<div>
<div class="docs-crumbs">${esc(article.section_title || '')}</div>
<h1>${esc(article.title)}</h1>
</div>
<div class="docs-article-actions">${actions.join('')}</div>
</div>
<div class="docs-meta">${meta.join('')}</div>
<div class="docs-body">${WhatIDoMD.render(article.body)}</div>
${attachmentsHtml(article)}
</article>`;
}
function attachmentsHtml(article) {
const images = article.images || [];
const files = article.files || [];
if (!images.length && !files.length) return '';
const editable = !!article.can_edit;
const imagesBlock = images.length ? `<div class="docs-attachments-title">Картинки</div>
<ul class="docs-attachments-list docs-attachments-images">${images.map(img => `<li class="docs-attach-image">
<a href="${esc(img.path)}" target="_blank" rel="noopener"><img src="${esc(thumbSrc(img.path))}" alt="${esc(img.caption || '')}" loading="lazy"></a>
${editable
? captionRowHtml(img.id, img.caption, 'caption')
: (img.caption ? `<div class="docs-img-caption">${esc(img.caption)}</div>` : '')}
</li>`).join('')}</ul>` : '';
const filesBlock = files.length ? `<div class="docs-attachments-title">Файлы</div>
<ul class="docs-attachments-list">${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>` : '';
return `<div class="docs-attachments">${imagesBlock}${filesBlock}</div>`;
}
async function saveArticleImageCaption(id, caption) {
if (!id) return;
try {
const data = await req('/api/docs/images/' + encodeURIComponent(id), { method: 'PUT', body: JSON.stringify({ caption }) });
if (current) {
current.images = (current.images || []).map(x => String(x.id) === String(id) ? Object.assign({}, x, { caption: data.item.caption }) : x);
if (data.item.body != null && Number(data.item.article_id) === Number(current.id)) current.body = data.item.body;
renderArticle();
}
showToast('Подпись сохранена');
} catch (e) {
showToast(e.message, true);
}
}
function renderArticle() {
if (!current) return renderEmpty();
contentEl.hidden = false;
editorEl.hidden = true;
contentEl.innerHTML = articleHtml(current);
markActive();
renderIconsSafe();
}
function markActive() {
treeEl.querySelectorAll('.docs-article-row a').forEach(a => {
a.classList.toggle('active', !!current && a.dataset.slug === current.slug);
});
}
async function openArticle(slug, updateHash) {
if (editState && editState.dirty && !confirm('Несохранённые изменения будут потеряны. Продолжить?')) return;
const data = await req('/api/docs/articles/' + encodeURIComponent(slug));
current = data.item;
try {
const [fdata, idata] = await Promise.all([
req('/api/docs/articles/' + current.id + '/files'),
req('/api/docs/articles/' + current.id + '/images'),
]);
current.files = fdata.items || [];
current.images = idata.items || [];
} catch (e) { current.files = []; current.images = []; }
editState = null;
if (updateHash !== false) history.replaceState(null, '', '#a=' + encodeURIComponent(current.slug));
renderArticle();
markActive();
}
function fillSectionSelect(selectedId) {
const list = sectionList().filter(s => isAdmin() || s.can_write);
sectionEl.innerHTML = list.map(s => {
const prefix = s.depth ? '\u00A0\u00A0'.repeat(s.depth) + '— ' : '';
return `<option value="${s.id}">${esc(prefix + s.title)}</option>`;
}).join('');
if (selectedId && list.some(s => Number(s.id) === Number(selectedId))) sectionEl.value = String(selectedId);
return list.length > 0;
}
function markDirty() {
if (!editState) return;
editState.dirty = true;
hintEl.textContent = 'Есть несохранённые изменения';
}
function updatePreview() {
previewEl.innerHTML = bodyEl.value.trim()
? WhatIDoMD.render(bodyEl.value)
: '<div class="docs-preview-empty">Предпросмотр появится здесь</div>';
}
function schedulePreview() {
clearTimeout(previewTimer);
previewTimer = setTimeout(updatePreview, 150);
}
function startEdit(article, presetSectionId) {
if (article && !article.can_edit) {
showToast('Нет прав на редактирование этой статьи', true);
return;
}
const list = sectionList().filter(s => isAdmin() || s.can_write);
if (!list.length) {
showToast('Нет разделов, где вам разрешено писать', true);
return;
}
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;
publicEl.checked = article ? article.is_public : false;
publicWrap.hidden = !isAdmin();
const preferred = article ? article.section_id : (presetSectionId || (current && current.section_id));
fillSectionSelect(preferred);
hintEl.textContent = '';
contentEl.hidden = true;
editorEl.hidden = false;
updatePreview();
renderIconsSafe();
titleEl.focus();
titleEl.select();
}
function closeEditor() {
editorEl.hidden = true;
contentEl.hidden = false;
editState = null;
hintEl.textContent = '';
}
function cancelEdit() {
if (editState && editState.dirty && !confirm('Отменить несохранённые изменения?')) return;
closeEditor();
if (current) renderArticle(); else renderEmpty();
}
async function saveArticle() {
if (!editState) return;
const title = titleEl.value.trim();
if (!title) { showToast('Введите заголовок статьи', true); titleEl.focus(); return; }
const sectionId = parseInt(sectionEl.value, 10);
if (!Number.isInteger(sectionId) || sectionId < 1) { showToast('Выберите раздел', true); return; }
const payload = {
section_id: sectionId,
title,
body: bodyEl.value,
is_published: publishedEl.checked,
is_public: isAdmin() ? publicEl.checked : false,
};
const saveBtn = el('docsSaveBtn');
const pendingFileIds = (editState && editState.files ? editState.files : []).filter(f => !f.article_id && f._kind !== 'image').map(f => f.id);
saveBtn.disabled = true;
try {
const path = editState.id ? '/api/docs/articles/' + editState.id : '/api/docs/articles';
const method = editState.id ? 'PUT' : 'POST';
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('Статья сохранена');
} catch (e) {
showToast(e.message, true);
} finally {
saveBtn.disabled = false;
}
}
async function deleteArticle() {
if (!current || !current.can_edit) return;
if (!confirm(`Удалить статью «${current.title}»? Действие необратимо.`)) return;
try {
await req('/api/docs/articles/' + current.id, { method: 'DELETE' });
const slug = current.slug;
current = null;
history.replaceState(null, '', location.pathname);
await loadTree();
renderEmpty();
showToast('Статья удалена');
} catch (e) {
showToast(e.message, true);
}
}
function copyPublicLink() {
if (!current) return;
const url = `${location.origin}/docs-public.html?slug=${encodeURIComponent(current.slug)}`;
const done = () => showToast('Ссылка скопирована');
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url).then(done).catch(() => prompt('Публичная ссылка', url));
} else {
prompt('Публичная ссылка', url);
}
}
function applyWrap(before, after, fallback) {
const start = bodyEl.selectionStart;
const end = bodyEl.selectionEnd;
const selected = bodyEl.value.slice(start, end);
const inner = selected || fallback || '';
bodyEl.setRangeText(before + inner + after, start, end, 'end');
bodyEl.focus();
if (!selected && inner) {
bodyEl.setSelectionRange(start + before.length, start + before.length + inner.length);
}
markDirty();
updatePreview();
}
function applyPrefix(prefix) {
const start = bodyEl.selectionStart;
const lineStart = bodyEl.value.lastIndexOf('\n', start - 1) + 1;
bodyEl.setRangeText(prefix, lineStart, lineStart, 'end');
bodyEl.focus();
markDirty();
updatePreview();
}
function insertBlock(text) {
const start = bodyEl.selectionStart;
const before = bodyEl.value.slice(0, start);
const prefix = before && !before.endsWith('\n') ? '\n' : '';
bodyEl.setRangeText(prefix + text + '\n', start, bodyEl.selectionEnd, 'end');
bodyEl.focus();
markDirty();
updatePreview();
renderDocFilesTable();
}
function applyToolbar(kind) {
if (kind === 'bold') return applyWrap('**', '**', 'жирный текст');
if (kind === 'italic') return applyWrap('*', '*', 'курсив');
if (kind === 'strike') return applyWrap('~~', '~~', 'зачёркнутый');
if (kind === 'code') return applyWrap('`', '`', 'код');
if (kind === 'h2') return applyPrefix('## ');
if (kind === 'h3') return applyPrefix('### ');
if (kind === 'ul') return applyPrefix('- ');
if (kind === 'ol') return applyPrefix('1. ');
if (kind === 'quote') return applyPrefix('> ');
if (kind === 'hr') return insertBlock('---');
if (kind === 'link') return applyWrap('[', '](https://)', 'текст ссылки');
if (kind === 'table') return insertBlock('| Колонка | Колонка |\n| --- | --- |\n| | |');
if (kind === 'image') { const uploadBtn = el('docsFileUploadBtn'); if (uploadBtn) uploadBtn.click(); return; }
}
async function uploadImage(file, articleId) {
if (!fileIsImage(file)) {
showToast('Можно вставлять только изображения', true);
return;
}
showToast('Загрузка картинки...');
try {
const form = new FormData();
form.append('image', file);
if (articleId) form.append('article_id', String(articleId));
const data = await req('/api/docs/images', { method: 'POST', body: form });
insertBlock(`![](${data.item.path})`);
showToast('Картинка добавлена');
} catch (e) {
showToast(e.message, true);
}
}
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 => imageItem(x, { _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 => imageItem(x));
editState.files = files.concat(images);
renderDocFilesTable();
} catch (e) {
editState.files = [];
renderDocFilesTable();
}
}
function imageItem(x, extra) {
return Object.assign({
id: x.id,
article_id: x.article_id == null ? null : x.article_id,
path: x.path,
caption: x.caption || '',
name: (x.path || '').split('/').pop(),
size_bytes: null,
mime: 'image/*',
_kind: 'image',
}, extra || {});
}
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) || [];
const known = new Set(files.map(f => f.path));
const extra = bodyImages().filter(x => !known.has(x.path));
if (!files.length && !extra.length) {
filesBodyEl.innerHTML = '<tr><td colspan="4" class="docs-empty" style="padding:8px">Вложений пока нет</td></tr>';
return;
}
const rows = files.map(f => {
const isImg = f._kind === 'image' || isImageFile(f);
const thumb = isImg ? `<img src="${esc(thumbSrc(f.path))}" alt="" style="width:36px;height:36px;object-fit:cover;border-radius:6px;vertical-align:middle;margin-right:6px">` : '';
const acts = f._unattached
? (f._kind === 'image'
? `<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="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>`)
: (f._kind === 'image'
? `<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 ? captionRowHtml(f.id, f.caption || bodyImageCaption(f.path), 'caption') : '';
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>`;
});
const extraRows = extra.map(x => {
const name = x.path.split('/').pop();
return `<tr data-file-id="body:${esc(x.path)}" data-file-kind="image">
<td><img src="${esc(thumbSrc(x.path))}" alt="" style="width:36px;height:36px;object-fit:cover;border-radius:6px;vertical-align:middle;margin-right:6px"><a href="${esc(x.path)}" target="_blank" rel="noopener">${esc(name)}</a>${captionRowHtml('body:' + x.path, x.caption, 'caption')}</td>
<td>—</td>
<td><span class="docs-badge">В тексте</span></td>
<td class="docs-files-acts"></td>
</tr>`;
});
filesBodyEl.innerHTML = rows.concat(extraRows).join('');
}
function captionRowHtml(id, caption, action) {
return `<div class="docs-caption-row"><input class="docs-caption-input" data-caption-for="${esc(id)}" value="${esc(caption || '')}" placeholder="Подпись (alt/title)" maxlength="300"><button type="button" class="btn-primary ghost" data-file-act="${action}" title="Сохранить подпись">✓</button></div>`;
}
function bodyImages() {
const body = bodyEl.value || '';
const out = [];
const seen = new Set();
const re = /!\[([^\]]*)\]\(([^)\s]+)\)/g;
let m;
while ((m = re.exec(body))) {
if (!IMAGE_EXT_RE.test(m[2]) || seen.has(m[2])) continue;
seen.add(m[2]);
out.push({ path: m[2], caption: m[1] });
}
return out;
}
function bodyImageCaption(path) {
const found = bodyImages().find(x => x.path === path);
return found ? found.caption : '';
}
function updateBodyImageCaption(path, caption) {
const body = bodyEl.value || '';
const escPath = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp('!\\[([^\\]]*)\\]\\(' + escPath + '\\)', 'g');
const alt = String(caption || '').replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
const next = body.replace(re, '![' + alt + '](' + path + ')');
if (next === body) return false;
bodyEl.value = next;
markDirty();
updatePreview();
return true;
}
async function uploadDocFile(file, articleId) {
if (!file) return null;
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(Object.assign({}, data.item, { _kind: 'file' }));
renderDocFilesTable();
}
showToast('Файл прикреплён');
return data.item;
} catch (e) {
showToast(e.message, true);
return null;
}
}
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) && f._kind !== 'image') ? Object.assign({}, data.item, { _kind: 'file' }) : 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) && f._kind !== 'image'));
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) && f._kind !== 'image'));
renderDocFilesTable();
}
showToast('Файл удалён');
} catch (e) {
showToast(e.message, true);
}
}
function isImageFile(f) {
const mime = String(f.mime || '').toLowerCase();
if (mime.startsWith('image/')) return true;
return IMAGE_EXT_RE.test(String(f.name || f.path || ''));
}
function fileIsImage(f) {
return !!f && ((!!f.type && f.type.startsWith('image/')) || IMAGE_EXT_RE.test(f.name || ''));
}
function insertDocFileLink(f) {
const isImg = isImageFile(f);
const label = String(isImg ? (f.caption || '') : (f.name || 'файл')).replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
const md = isImg ? `![${label}](${f.path})` : `[${label}](${f.path})`;
insertBlock(md);
}
async function loadUnattachedDocFiles() {
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 => imageItem(x, { _unattached: true }));
const items = files.concat(images);
if (!items.length) { showToast('Нет неприкреплённых файлов', true); return; }
const prev = (editState && editState.files) || [];
const seen = new Set(prev.map(x => (x._kind || 'file') + ':' + (x.id != null ? x.id : x.path)));
const merged = prev.concat(items.filter(x => !seen.has((x._kind || 'file') + ':' + (x.id != null ? x.id : x.path))));
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)}" data-img-caption="${esc(it.caption || '')}" 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>
${it.caption ? '<div class="docs-imglib-caption">' + esc(it.caption) + '</div>' : ''}
</div>`).join('');
} catch (e) {
imgLibGrid.innerHTML = '<div class="docs-empty">' + esc(e.message) + '</div>';
}
}
async function loadAllDocFiles() {
try {
const [fdata, idata] = await Promise.all([
req('/api/docs/files'),
req('/api/docs/images'),
]);
const files = (fdata.items || []).map(x => Object.assign({}, x, { _kind: 'file', _all: true }));
const images = (idata.items || []).map(x => imageItem(x, { _all: true }));
if (editState) {
const curId = editState.id;
editState.files = files.concat(images).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 => {
const prefix = s.depth ? '\u00A0\u00A0'.repeat(s.depth) + '— ' : '';
return `<option value="${s.id}">${esc(prefix + s.title)}</option>`;
}).join('');
sectionParentEl.value = selectedId ? String(selectedId) : '';
}
function openSectionModal(id, parentId) {
const section = id ? findSection(id) : null;
sectionEditId = section ? Number(section.id) : null;
el('docsSectionModalTitle').textContent = section ? 'Изменить раздел' : 'Новый раздел';
sectionTitleEl.value = section ? section.title : '';
sectionTutorEl.checked = section ? !!section.tutor_edit : false;
sectionPublicEl.checked = section ? !!section.is_public : false;
fillParentSelect(section ? section.id : null, section ? section.parent_id : (parentId || null));
sectionDeleteBtn.style.display = section ? '' : 'none';
sectionModal.classList.add('open');
sectionTitleEl.focus();
sectionTitleEl.select();
}
function closeSectionModal() {
sectionModal.classList.remove('open');
sectionEditId = null;
}
async function saveSection() {
const title = sectionTitleEl.value.trim();
if (!title) { showToast('Введите название раздела', true); sectionTitleEl.focus(); return; }
const payload = {
title,
parent_id: sectionParentEl.value ? parseInt(sectionParentEl.value, 10) : null,
tutor_edit: sectionTutorEl.checked,
is_public: sectionPublicEl.checked,
};
try {
const path = sectionEditId ? '/api/docs/sections/' + sectionEditId : '/api/docs/sections';
await req(path, { method: sectionEditId ? 'PUT' : 'POST', body: JSON.stringify(payload) });
closeSectionModal();
await loadTree();
if (current) {
try { await openArticle(current.slug); } catch (e) {}
}
showToast('Раздел сохранён');
} catch (e) {
showToast(e.message, true);
}
}
function countArticles(node) {
let total = (node.articles || []).length;
for (const child of node.children || []) total += countArticles(child);
return total;
}
async function deleteSection() {
if (!sectionEditId) return;
const node = findSectionNode(sectionEditId);
const count = node ? countArticles(node) : 0;
const warning = count ? ` Вместе с ним удалятся статьи: ${count}.` : '';
if (!confirm(`Удалить раздел «${sectionTitleEl.value.trim()}»?${warning}`)) return;
try {
const id = sectionEditId;
await req('/api/docs/sections/' + id, { method: 'DELETE' });
closeSectionModal();
await loadTree();
if (current) {
try { await openArticle(current.slug); } catch (e) { current = null; history.replaceState(null, '', location.pathname); renderEmpty(); }
}
showToast('Раздел удалён');
} catch (e) {
showToast(e.message, true);
}
}
async function moveSection(id, direction) {
const section = findSection(id);
if (!section) return;
const siblings = sectionList().filter(s => String(s.parent_id || '') === String(section.parent_id || ''));
const index = siblings.findIndex(s => Number(s.id) === Number(id));
const target = index + direction;
if (index < 0 || target < 0 || target >= siblings.length) return;
const swap = siblings[index];
siblings[index] = siblings[target];
siblings[target] = swap;
try {
await req('/api/docs/sections/reorder', {
method: 'PUT',
body: JSON.stringify({ ids: siblings.map(s => s.id) }),
});
await loadTree();
} catch (e) {
showToast(e.message, true);
}
}
async function moveArticle(id, sectionId, direction) {
const node = findSectionNode(sectionId);
if (!node) return;
const articles = (node.articles || []).slice();
const index = articles.findIndex(a => Number(a.id) === Number(id));
const target = index + direction;
if (index < 0 || target < 0 || target >= articles.length) return;
const swap = articles[index];
articles[index] = articles[target];
articles[target] = swap;
try {
await req('/api/docs/articles/reorder', {
method: 'PUT',
body: JSON.stringify({ section_id: Number(sectionId), ids: articles.map(a => a.id) }),
});
await loadTree();
} catch (e) {
showToast(e.message, true);
}
}
async function runSearch() {
const query = searchEl.value.trim();
if (query.length < 2) { renderTree(); return; }
try {
const data = await req('/api/docs/search?q=' + encodeURIComponent(query));
if (!data.items.length) {
treeEl.innerHTML = '<div class="docs-empty">Ничего не найдено</div>';
return;
}
treeEl.innerHTML = `<div class="docs-search-results">${data.items.map(item => {
const excerpt = String(item.excerpt || '').replace(/\s+/g, ' ').trim();
return `<div class="docs-search-item" data-slug="${esc(item.slug)}">
<b>${esc(item.title)}</b>
<span>${esc(excerpt)}</span>
<em>${esc(item.section_title || '')}</em>
</div>`;
}).join('')}</div>`;
} catch (e) {
showToast(e.message, true);
}
}
function bindTree() {
treeEl.addEventListener('click', e => {
const act = e.target.closest('[data-act]');
if (act) {
e.preventDefault();
e.stopPropagation();
const id = parseInt(act.dataset.id, 10);
const action = act.dataset.act;
if (action === 'add-article') return startEdit(null, id);
if (action === 'add-sub') return openSectionModal(null, id);
if (action === 'edit-section') return openSectionModal(id, null);
if (action === 'section-up') return moveSection(id, -1);
if (action === 'section-down') return moveSection(id, 1);
if (action === 'article-up') return moveArticle(id, parseInt(act.dataset.section, 10), -1);
if (action === 'article-down') return moveArticle(id, parseInt(act.dataset.section, 10), 1);
return;
}
const toggle = e.target.closest('[data-toggle]');
if (toggle) {
e.preventDefault();
e.stopPropagation();
const id = Number(toggle.dataset.toggle);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
return;
}
const link = e.target.closest('[data-slug]');
if (link) {
e.preventDefault();
openArticle(link.dataset.slug).catch(err => showToast(err.message, true));
return;
}
const row = e.target.closest('.docs-section-row');
if (row) {
const id = Number(row.dataset.section);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
}
});
}
function bindEditor() {
el('docsToolbar').addEventListener('click', e => {
const btn = e.target.closest('[data-md]');
if (!btn) return;
e.preventDefault();
applyToolbar(btn.dataset.md);
});
bodyEl.addEventListener('input', () => { markDirty(); schedulePreview(); });
bodyEl.addEventListener('dragover', e => {
if (!e.dataTransfer || ![...e.dataTransfer.types].includes('Files')) return;
e.preventDefault();
bodyEl.classList.add('docs-drop');
});
bodyEl.addEventListener('dragleave', () => bodyEl.classList.remove('docs-drop'));
bodyEl.addEventListener('drop', async e => {
const files = [...(e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : [])];
if (!files.length) return;
e.preventDefault();
bodyEl.classList.remove('docs-drop');
const aidDrop = editState && editState.id ? editState.id : null;
for (const file of files) {
if (fileIsImage(file)) await uploadImage(file, aidDrop);
else await uploadDocFile(file, aidDrop);
}
await loadDocFiles(aidDrop);
});
bodyEl.addEventListener('paste', async e => {
const data = e.clipboardData;
if (!data) return;
const files = [...(data.files || [])].filter(f => fileIsImage(f));
if (!files.length) return;
e.preventDefault();
const aidPaste = editState && editState.id ? editState.id : null;
for (const file of files) await uploadImage(file, aidPaste);
await loadDocFiles(aidPaste);
});
[titleEl, sectionEl, publishedEl, publicEl].forEach(control => {
control.addEventListener('input', markDirty);
control.addEventListener('change', markDirty);
});
imageFileEl.addEventListener('change', async () => {
const file = imageFileEl.files && imageFileEl.files[0];
imageFileEl.value = '';
const aidImg = editState && editState.id ? editState.id : null;
if (file) await uploadImage(file, aidImg);
await loadDocFiles(aidImg);
});
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) {
if (fileIsImage(f)) {
await uploadImage(f, aid);
} else {
await uploadDocFile(f, 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 caption = (item.dataset.imgCaption || '').replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
insertBlock(`![${caption}](${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 : '';
const kind = tr.dataset.fileKind || (f && f._kind) || 'file';
if (String(id).startsWith('body:')) {
const path = String(id).slice(5);
if (updateBodyImageCaption(path, val)) showToast('Подпись сохранена');
else showToast('Картинка не найдена в тексте', true);
renderDocFilesTable();
return;
}
const sameArticle = !f || !f.article_id || (editState && Number(f.article_id) === Number(editState.id));
if (kind !== 'image' || !sameArticle) {
if (f && updateBodyImageCaption(f.path, val)) showToast('Подпись сохранена');
else showToast('Картинка не вставлена в текст', true);
renderDocFilesTable();
return;
}
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) ? Object.assign({}, x, { caption: data.item.caption }) : x);
if (f && f.path) updateBodyImageCaption(f.path, val);
renderDocFilesTable();
}
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) && x._kind !== 'image') ? Object.assign({}, data.item, { _kind: 'file' }) : x).filter(x => x.article_id);
renderDocFilesTable();
}
showToast('Файл прикреплён');
}).catch(err => showToast(err.message, true));
}
});
if (filesBodyEl) filesBodyEl.addEventListener('keydown', e => {
if (e.key !== 'Enter') return;
const input = e.target.closest('.docs-caption-input');
if (!input) return;
e.preventDefault();
const btn = input.parentElement.querySelector('[data-file-act="caption"]');
if (btn) btn.click();
});
el('docsSaveBtn').addEventListener('click', saveArticle);
el('docsCancelBtn').addEventListener('click', cancelEdit);
}
function bindPage() {
el('docsNewArticleBtn').addEventListener('click', () => startEdit(null, current ? current.section_id : null));
el('docsNewSectionBtn').addEventListener('click', () => openSectionModal(null, null));
contentEl.addEventListener('click', e => {
const capBtn = e.target.closest('[data-file-act="caption"]');
if (capBtn) {
const row = capBtn.closest('.docs-caption-row');
const input = row ? row.querySelector('.docs-caption-input') : null;
if (input) saveArticleImageCaption(input.dataset.captionFor, input.value);
return;
}
const btn = e.target.closest('[data-doc-act]');
if (!btn) return;
const action = btn.dataset.docAct;
if (action === 'edit') startEdit(current);
if (action === 'delete') deleteArticle();
if (action === 'copy') copyPublicLink();
});
contentEl.addEventListener('keydown', e => {
if (e.key !== 'Enter') return;
const input = e.target.closest('.docs-caption-input');
if (!input) return;
e.preventDefault();
saveArticleImageCaption(input.dataset.captionFor, input.value);
});
searchEl.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(runSearch, 250);
});
el('docsSectionSave').addEventListener('click', saveSection);
el('docsSectionCancel').addEventListener('click', closeSectionModal);
sectionDeleteBtn.addEventListener('click', deleteSection);
sectionModal.addEventListener('click', e => { if (e.target === sectionModal) closeSectionModal(); });
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && sectionModal.classList.contains('open')) closeSectionModal();
if ((e.ctrlKey || e.metaKey) && e.key === 's' && editState) {
e.preventDefault();
saveArticle();
}
});
window.addEventListener('beforeunload', e => {
if (editState && editState.dirty) {
e.preventDefault();
e.returnValue = '';
}
});
}
function firstSlug(nodes) {
for (const node of (nodes || [])) {
if (node.articles && node.articles.length) return node.articles[0].slug;
const nested = firstSlug(node.children || []);
if (nested) return nested;
}
return '';
}
async function init() {
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
if (!isAdmin()) el('docsNewSectionBtn').hidden = true;
bindTree();
bindEditor();
bindPage();
renderIconsSafe();
try {
await loadTree();
} catch (e) {
showToast(e.message, true);
}
const hash = location.hash.replace(/^#a=/, '');
if (hash) {
try {
await openArticle(decodeURIComponent(hash), false);
} catch (e) {
const slug = firstSlug(tree);
if (slug) {
try { await openArticle(slug, true); } catch (e2) { renderEmpty(); }
} else {
renderEmpty();
}
}
} else {
const slug = firstSlug(tree);
if (slug) {
try { await openArticle(slug, true); } catch (e) { renderEmpty(); }
} else {
renderEmpty();
}
}
renderIconsSafe();
}
init();
})();