wip: скрытые группы, документация, прочие изменения
This commit is contained in:
+246
-63
@@ -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(``);
|
||||
insertBlock(``);
|
||||
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, '');
|
||||
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) ? `` : `[${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})`;
|
||||
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(``);
|
||||
const caption = (item.dataset.imgCaption || '').replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
|
||||
insertBlock(``);
|
||||
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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user