wip: скрытые группы, документация, прочие изменения

This commit is contained in:
dev
2026-11-03 12:06:45 +03:00
parent 6685800cf4
commit 183ca47f17
11 changed files with 354 additions and 86 deletions
+246 -63
View File
@@ -33,6 +33,7 @@
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) || '[]');
@@ -170,11 +171,11 @@
function articleHtml(article) {
const actions = [];
if (article.can_edit) {
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="edit">Редактировать</button>');
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="delete" style="color:#ef4444;border-color:rgba(239,68,68,.35)">Удалить</button>');
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">Скопировать публичную ссылку</button>');
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>`);
@@ -182,24 +183,58 @@
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-crumbs">${esc(article.section_title || '')}</div>
<h1>${esc(article.title)}</h1>
<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-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 => { const isImg = f._kind === 'image'; 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 `<li><a href="${esc(f.path)}" target="_blank" rel="noopener">${esc(f.name)}</a>${captionInput} <span class="docs-attach-size">${fmtBytes(f.size_bytes)}</span></li>`; }).join('')}</ul>
</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() {
@@ -213,9 +248,13 @@
const data = await req('/api/docs/articles/' + encodeURIComponent(slug));
current = data.item;
try {
const fdata = await req('/api/docs/articles/' + current.id + '/files');
const [fdata, idata] = await Promise.all([
req('/api/docs/articles/' + current.id + '/files'),
req('/api/docs/articles/' + current.id + '/images'),
]);
current.files = fdata.items || [];
} catch (e) { current.files = []; }
current.images = idata.items || [];
} catch (e) { current.files = []; current.images = []; }
editState = null;
if (updateHash !== false) history.replaceState(null, '', '#a=' + encodeURIComponent(current.slug));
renderArticle();
@@ -304,7 +343,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);
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';
@@ -383,6 +422,7 @@
bodyEl.focus();
markDirty();
updatePreview();
renderDocFilesTable();
}
function applyToolbar(kind) {
@@ -398,11 +438,11 @@
if (kind === 'hr') return insertBlock('---');
if (kind === 'link') return applyWrap('[', '](https://)', 'текст ссылки');
if (kind === 'table') return insertBlock('| Колонка | Колонка |\n| --- | --- |\n| | |');
if (kind === 'image') { imageFileEl.click(); return; }
if (kind === 'image') { const uploadBtn = el('docsFileUploadBtn'); if (uploadBtn) uploadBtn.click(); return; }
}
async function uploadImage(file) {
if (!file || !file.type || !file.type.startsWith('image/')) {
async function uploadImage(file, articleId) {
if (!fileIsImage(file)) {
showToast('Можно вставлять только изображения', true);
return;
}
@@ -410,9 +450,9 @@
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 });
const alt = (file.name || 'картинка').replace(/\.[^.]+$/, '');
insertBlock(`![${alt}](${data.item.path})`);
insertBlock(`![](${data.item.path})`);
showToast('Картинка добавлена');
} catch (e) {
showToast(e.message, true);
@@ -436,7 +476,7 @@
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 }));
const images = (idata.items || []).map(x => imageItem(x, { _unattached: true }));
editState.files = files.concat(images);
renderDocFilesTable();
} catch (e) {
@@ -451,7 +491,7 @@
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/*' }));
const images = (idata.items || []).map(x => imageItem(x));
editState.files = files.concat(images);
renderDocFilesTable();
} catch (e) {
@@ -460,6 +500,19 @@
}
}
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;
@@ -471,19 +524,22 @@
function renderDocFilesTable() {
if (!filesBodyEl) return;
const files = (editState && editState.files) || [];
if (!files.length) {
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;
}
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 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
? (isImg
? `<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="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
: (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>
@@ -491,18 +547,64 @@
<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>` : '';
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>`;
}).join('');
});
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;
if (!file) return null;
showToast('Загрузка файла...');
try {
const form = new FormData();
@@ -511,12 +613,14 @@
const data = await req('/api/docs/files', { method: 'POST', body: form });
if (editState) {
editState.files = editState.files || [];
editState.files.unshift(data.item);
editState.files.unshift(Object.assign({}, data.item, { _kind: 'file' }));
renderDocFilesTable();
}
showToast('Файл прикреплён');
return data.item;
} catch (e) {
showToast(e.message, true);
return null;
}
}
@@ -538,7 +642,7 @@
updatePreview();
}
if (editState) {
editState.files = (editState.files || []).map(f => Number(f.id) === Number(id) ? data.item : f);
editState.files = (editState.files || []).map(f => (Number(f.id) === Number(id) && f._kind !== 'image') ? Object.assign({}, data.item, { _kind: 'file' }) : f);
renderDocFilesTable();
}
showToast('Файл заменён');
@@ -554,7 +658,7 @@
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));
editState.files = (editState.files || []).filter(f => !(Number(f.id) === Number(id) && f._kind !== 'image'));
renderDocFilesTable();
}
showToast('Файл откреплён');
@@ -568,7 +672,7 @@
try {
await req('/api/docs/files/' + id, { method: 'DELETE' });
if (editState) {
editState.files = (editState.files || []).filter(f => Number(f.id) !== Number(id));
editState.files = (editState.files || []).filter(f => !(Number(f.id) === Number(id) && f._kind !== 'image'));
renderDocFilesTable();
}
showToast('Файл удалён');
@@ -580,21 +684,31 @@
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 || ''));
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 alt = (f.caption || f.name || 'картинка').replace(/\\./g, '\\.');
const md = isImageFile(f) ? `![${alt}](${f.path})` : `[${f.name}](${f.path})`;
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 data = await req('/api/docs/files/unattached');
const items = data.items || [];
if (!items.length) { showToast('Нет незагруженных файлов', true); return; }
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 merged = prev.concat(items.map(x => Object.assign({}, x, { _unattached: true })));
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);
@@ -625,12 +739,15 @@
async function loadAllDocFiles() {
try {
const data = await req('/api/docs/files');
const items = (data.items || []).map(x => Object.assign({}, x, { _all: true }));
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) {
// 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) }));
editState.files = files.concat(images).map(x => Object.assign({}, x, { _unattached: !x.article_id || Number(x.article_id) !== Number(curId) }));
renderDocFilesTable();
}
} catch (e) {
@@ -841,15 +958,22 @@
if (!files.length) return;
e.preventDefault();
bodyEl.classList.remove('docs-drop');
for (const file of files) await uploadImage(file);
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 => f.type && f.type.startsWith('image/'));
const files = [...(data.files || [])].filter(f => fileIsImage(f));
if (!files.length) return;
e.preventDefault();
for (const file of files) await uploadImage(file);
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);
@@ -858,14 +982,22 @@
imageFileEl.addEventListener('change', async () => {
const file = imageFileEl.files && imageFileEl.files[0];
imageFileEl.value = '';
if (file) await uploadImage(file);
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) await uploadDocFile(f, aid);
if (aid) await loadDocFiles(aid);
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());
@@ -889,9 +1021,8 @@
if (!item) return;
const p = item.dataset.imgPath;
if (!p) return;
const caption = item.dataset.imgCaption || '';
const alt = caption || p.split("/").pop().replace(/\.[^.]+$/, "");
insertBlock(`![${alt}](${p})`);
const caption = (item.dataset.imgCaption || '').replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
insertBlock(`![${caption}](${p})`);
if (imgLibModal) imgLibModal.classList.remove('open');
showToast('Картинка вставлена');
});
@@ -907,17 +1038,28 @@
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) && x._kind === 'image' ? Object.assign({}, x, { caption: data.item.caption }) : x);
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();
}
if (data.item.body && editState) {
bodyEl.value = data.item.body;
markDirty();
updatePreview();
}
showToast('Подпись сохранена');
}).catch(err => showToast(err.message, true));
return;
@@ -944,13 +1086,21 @@
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);
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);
}
@@ -959,6 +1109,13 @@
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;
@@ -966,6 +1123,13 @@
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);
@@ -989,6 +1153,15 @@
});
}
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);
@@ -1007,10 +1180,20 @@
try {
await openArticle(decodeURIComponent(hash), false);
} catch (e) {
renderEmpty();
const slug = firstSlug(tree);
if (slug) {
try { await openArticle(slug, true); } catch (e2) { renderEmpty(); }
} else {
renderEmpty();
}
}
} else {
renderEmpty();
const slug = firstSlug(tree);
if (slug) {
try { await openArticle(slug, true); } catch (e) { renderEmpty(); }
} else {
renderEmpty();
}
}
renderIconsSafe();
}
+28 -5
View File
@@ -12,9 +12,9 @@ let groupFilters = loadGroupFilters();
function loadGroupFilters() {
try {
const d = JSON.parse(localStorage.getItem(GROUPS_FILTER_KEY) || 'null');
if (d && typeof d === 'object') return { branch: String(d.branch ?? ''), tutor: String(d.tutor ?? ''), day: String(d.day ?? '') };
if (d && typeof d === 'object') return { branch: String(d.branch ?? ''), tutor: String(d.tutor ?? ''), day: String(d.day ?? ''), showHidden: !!d.showHidden };
} catch (e) {}
return { branch: '', tutor: '', day: '' };
return { branch: '', tutor: '', day: '', showHidden: false };
}
function saveGroupFilters() {
@@ -39,6 +39,8 @@ function renderGroupFilters() {
groupFilters.branch = pickFilterValue(branchSel, groupFilters.branch);
groupFilters.tutor = pickFilterValue(tutorSel, groupFilters.tutor);
groupFilters.day = pickFilterValue(daySel, groupFilters.day);
const showHiddenEl = document.getElementById('groupShowHidden');
if (showHiddenEl) showHiddenEl.checked = !!groupFilters.showHidden;
if (before !== JSON.stringify(groupFilters)) saveGroupFilters();
}
@@ -52,6 +54,7 @@ function groupMatchesFilters(g) {
if (groupFilters.day === 'none') {
if (g.day_of_week != null) return false;
} else if (groupFilters.day && String(g.day_of_week ?? '') !== groupFilters.day) return false;
if (!groupFilters.showHidden && g.hidden) return false;
return true;
}
@@ -67,11 +70,17 @@ function initGroupFilters() {
});
const reset = document.getElementById('groupFiltersReset');
if (reset) reset.addEventListener('click', () => {
groupFilters = { branch: '', tutor: '', day: '' };
groupFilters = { branch: '', tutor: '', day: '', showHidden: false };
saveGroupFilters();
renderGroupFilters();
renderGroups();
});
const showHiddenEl = document.getElementById('groupShowHidden');
if (showHiddenEl) showHiddenEl.addEventListener('change', () => {
groupFilters.showHidden = showHiddenEl.checked;
saveGroupFilters();
renderGroups();
});
}
async function loadBranchesCache() {
@@ -97,7 +106,7 @@ function branchSelectHTML(selectedId, disabled = false) {
async function loadGroups() {
await loadBranchesCache();
await loadTutorsCache();
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
const res = await fetch(`${API}/api/groups?include_hidden=1`, { headers: hdr() });
allGroups = await res.json();
renderGroupFilters();
renderGroups();
@@ -115,13 +124,16 @@ function renderGroups() {
const canEdit = admin || !!currentUser;
const canDelete = admin || (currentUser && Number(g.tutor_id) === Number(currentUser.id));
const schedSet = g.day_of_week != null && g.time_start && g.time_end;
const hidden = !!g.hidden;
return `
<div class="group-card" data-group-id="${g.id}">
<div class="group-card${hidden ? ' group-hidden' : ''}" data-group-id="${g.id}"${hidden ? ' style="opacity:.55"' : ''}>
${g.cover_path
? `<img class="group-cover" src="${thumbSrc(g.cover_path)}" data-img="${API}${g.cover_path}" loading="lazy" decoding="async" alt="">`
: `<div class="group-cover empty-cover">📷</div>`}
<div class="group-head">
<input class="name-input" id="name-${g.id}" value="${esc(g.name)}" ${canEdit ? '' : 'disabled'}>
${hidden ? `<span class="badge" style="font-size:.7rem;opacity:.7">Скрыта</span>` : ''}
${canDelete ? `<button class="hide-toggle" data-hide-group="${g.id}" title="${hidden ? 'Показать' : 'Скрыть'}"><i data-lucide="${hidden ? 'eye' : 'eye-off'}"></i></button>` : ''}
${canDelete ? `<button class="del" data-del-group="${g.id}" title="Удалить">&times;</button>` : ''}
</div>
<div class="group-schedule">
@@ -152,6 +164,7 @@ function renderGroups() {
</div>
</div>`;
}).join('') + `</div>`;
renderIcons();
}
async function saveGroup(id) {
@@ -208,6 +221,14 @@ async function delGroup(id) {
loadGroups();
}
async function toggleHideGroup(id) {
const g = allGroups.find(x => String(x.id) === String(id));
const newHidden = !(g && g.hidden);
const res = await fetch(`${API}/api/groups/${id}/hidden`, { method: 'PUT', headers: hdrJson(), body: JSON.stringify({ hidden: newHidden }) });
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
loadGroups();
}
const PHOTO_PAGE_SIZE = 24;
let currentGroupId = null;
let currentGroupName = '';
@@ -845,6 +866,8 @@ document.getElementById('groupList').addEventListener('click', e => {
if (sg) { saveGroup(parseInt(sg.dataset.saveGroup, 10)); return; }
const dg = e.target.closest('[data-del-group]');
if (dg) { delGroup(parseInt(dg.dataset.delGroup, 10)); return; }
const hg = e.target.closest('[data-hide-group]');
if (hg) { toggleHideGroup(parseInt(hg.dataset.hideGroup, 10)); return; }
const eg = e.target.closest('[data-export-group]');
if (eg) { exportGroup(parseInt(eg.dataset.exportGroup, 10), eg.dataset.groupName); return; }
const eu = e.target.closest('[data-export-urls]');