(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 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;
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(` `);
if (isAdmin()) {
acts.push(` `);
acts.push(` `);
acts.push(` `);
acts.push(` `);
}
return acts.join('');
}
function articleRow(article, depth) {
const active = current && Number(current.id) === Number(article.id);
const acts = isAdmin()
? `
`
: '';
return `
Выберите статью слева${canCreateAnywhere() ? ' или создайте новую' : ''}
`;
}
function articleHtml(article) {
const actions = [];
if (article.can_edit) {
actions.push('
${esc(article.section_title || '')}
${esc(article.title)}
${meta.join('')}
${actions.join('')}
${WhatIDoMD.render(article.body)}
`;
}
function renderArticle() {
if (!current) return renderEmpty();
contentEl.hidden = false;
editorEl.hidden = true;
contentEl.innerHTML = articleHtml(current);
markActive();
}
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;
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 `${data.items.map(item => {
const excerpt = String(item.excerpt || '').replace(/\s+/g, ' ').trim();
return `
${esc(item.title)}
${esc(excerpt)}
${esc(item.section_title || '')}
`;
}).join('')}
`;
} 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');
for (const file of files) await uploadImage(file);
});
bodyEl.addEventListener('paste', async e => {
const data = e.clipboardData;
if (!data) return;
const files = [...(data.files || [])].filter(f => f.type && f.type.startsWith('image/'));
if (!files.length) return;
e.preventDefault();
for (const file of files) await uploadImage(file);
});
[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 = '';
if (file) await uploadImage(file);
});
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 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();
});
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 = '';
}
});
}
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) {
renderEmpty();
}
} else {
renderEmpty();
}
renderIconsSafe();
}
init();
})();