wip: скрытые группы, документация, прочие изменения
This commit is contained in:
@@ -402,6 +402,8 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
|
||||
- `GET /api/docs/public/tree`, `GET /api/docs/public/articles/:slug` — **без авторизации**, под `apiLimiter`; статья отдаётся только если `is_public` у статьи, у её раздела и у всех родителей
|
||||
- **Связывание картинок с статьёй — по пути**: при `POST/PUT` статьи `linkImages()` обновляет `doc_images.article_id` для всех `NULL`-строк, чей `path` встречается в теле (`/uploads/<name>`); `pruneImages()` удаляет строки статьи, которых больше нет в Markdown, и возвращает пути — роут вызывает `safeUnlink` + `thumbUnlinkFor`. Поэтому картинку можно вставить до первого сохранения статьи (в том числе из буфера обмена), и она не потеряется
|
||||
- **`doc_images.path` и `doc_files.path` обязательны в `sweepOrphanedUploads()`** и в `BROKEN_IMAGE_SOURCES` — иначе sweep удалит файлы, на которые ссылается документация, или они не попадут в отчёт о битых изображениях
|
||||
- **Картинка — всегда `doc_images`, а не `doc_files`**: загрузка через «Картинка»/Ctrl+V/drag&drop идёт в `POST /api/docs/images` (`uploadImage`), поэтому у каждой картинки есть `caption` и строка с полем подписи. `ensureDocsTables()` при старте конвертирует legacy-строки `doc_files` с картинкой (mime `image/%` или расширение) в `doc_images` с тем же `path`/`article_id` — не возвращайте картинки в `doc_files` и не убирайте этот перенос, иначе у них снова пропадёт подпись
|
||||
- **Подпись картинки — `docs-caption-input`**: поле есть у каждой картинки и в таблице «Вложения» редактора (включая картинки, которые встречаются в теле, но ещё не зарегистрированы — у них `data-file-id="body:<path>"`), и у блока «Картинки» в просмотре статьи (только `can_edit`). Сохранение идёт `PUT /api/docs/images/:id`, сервер синхронизирует `caption` в alt Markdown (``, пустая подпись → ``); для строк без записи в `doc_images` alt правится локально в теле. Новые картинки вставляются как `` — имя файла подписью не становится
|
||||
- **Бэкап**: `doc_sections`/`doc_articles`/`doc_images`/`doc_files` входят в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, в `buildBackupArchive` (у `doc_files` там же отдельный `SELECT` — таблица была добавлена в списки нормализации раньше выгрузки, и архив молча отдаёт `doc_files: []`), в `normalizeRestoreData` (`docSections`/`docArticles`/`docImages`/`docFiles`, путь — `optUploadPath`) и в restore. Restore вставляет разделы сначала с `parent_id = NULL`, затем отдельным проходом проставляет родителей (иначе FK на ещё не вставленного родителя); у статей `author_id` и у картинок `article_id`/`uploaded_by` берутся через `(SELECT id …)`, отсутствующая ссылка даёт `NULL` (колонки nullable). `doc_images`/`doc_files` удаляются/вставляются вместе с остальными таблицами и до `users`
|
||||
- **`photo_jobs` в restore вставляются после `entry_photos`/`group_photos`**: существование `group_photo_id` проверяется селектом по `group_photos` — если цикл идёт раньше вставки самих групповых фото, все job'ы по фото групп молча пропускаются, а их `before_path`/`after_path` потом уносит `sweepOrphanedUploads`. Изменение состава `photo_jobs` или порядка restore-INSERT синхронизируй с этим правилом
|
||||
- **Markdown-рендерер — свой, без зависимостей**: `public/js/md.js` (`window.WhatIDoMD.render`). Разрешены заголовки h1–h4, параграфы, списки (в т.ч. вложенные и чекбоксы), цитаты, код (inline и блок), таблицы, `hr`, ссылки и картинки. HTML экранируется **до** разметки, URL пропускает только `http(s)` и `/uploads/<name>` — хранимый XSS через тело статьи невозможен, `DOMPurify`/`marked` не нужны. Картинки рендерятся через `thumbUrl()` (`thumbSrc`, если доступен) с полным путём в `data-img` — лайтбокс открывает оригинал
|
||||
|
||||
@@ -313,6 +313,7 @@ function normalizeRestoreData(data) {
|
||||
cover_path: optUploadPath(x.cover_path, 255),
|
||||
deleted_at: optTs(x.deleted_at),
|
||||
purge_at: optTs(x.purge_at),
|
||||
hidden: !!x.hidden,
|
||||
}));
|
||||
const students = (data.students || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
|
||||
+3
-1
@@ -23,11 +23,13 @@ CREATE TABLE IF NOT EXISTS groups (
|
||||
time_end TIME,
|
||||
cover_path VARCHAR(255),
|
||||
deleted_at TIMESTAMPTZ,
|
||||
purge_at TIMESTAMPTZ
|
||||
purge_at TIMESTAMPTZ,
|
||||
hidden BOOLEAN NOT NULL DEFAULT false
|
||||
);
|
||||
|
||||
ALTER TABLE groups ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE groups ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ;
|
||||
ALTER TABLE groups ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS modules (
|
||||
id SERIAL PRIMARY KEY,
|
||||
|
||||
@@ -160,6 +160,7 @@ ALTER TABLE groups ADD COLUMN IF NOT EXISTS time_end TIME;
|
||||
ALTER TABLE groups ADD COLUMN IF NOT EXISTS cover_path VARCHAR(255);
|
||||
ALTER TABLE groups ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE groups ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ;
|
||||
ALTER TABLE groups ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
|
||||
+15
-4
@@ -426,6 +426,16 @@ async function ensureDocsTables(pool) {
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_files_article ON doc_files(article_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_files_path ON doc_files(path)');
|
||||
await pool.query(`INSERT INTO doc_images (article_id, path, uploaded_by, created_at)
|
||||
SELECT df.article_id, df.path, df.uploaded_by, df.created_at
|
||||
FROM doc_files df
|
||||
WHERE (df.mime LIKE 'image/%' OR df.path ~* '\\.(png|jpe?g|gif|webp|bmp|avif|ico|heic|heif|jfif)$')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM doc_images di
|
||||
WHERE di.path = df.path AND di.article_id IS NOT DISTINCT FROM df.article_id
|
||||
)`);
|
||||
await pool.query(`DELETE FROM doc_files
|
||||
WHERE mime LIKE 'image/%' OR path ~* '\\.(png|jpe?g|gif|webp|bmp|avif|ico|heic|heif|jfif)$'`);
|
||||
const { rows } = await pool.query('SELECT 1 FROM doc_sections LIMIT 1');
|
||||
if (rows.length) {
|
||||
await refreshDefaultArticleBodies(pool);
|
||||
@@ -849,10 +859,11 @@ async function reorderArticles(pool, sectionId, ids) {
|
||||
}
|
||||
}
|
||||
|
||||
async function registerImage(pool, { path, userId }) {
|
||||
async function registerImage(pool, { path, userId, articleId }) {
|
||||
const aid = articleId == null || articleId === '' ? null : Number(articleId);
|
||||
const { rows } = await pool.query(
|
||||
'INSERT INTO doc_images (path, uploaded_by) VALUES ($1, $2) RETURNING id, path',
|
||||
[path, userId]
|
||||
'INSERT INTO doc_images (article_id, path, uploaded_by) VALUES ($1, $2, $3) RETURNING id, path, article_id',
|
||||
[aid, path, userId]
|
||||
);
|
||||
return rows[0];
|
||||
}
|
||||
@@ -906,7 +917,7 @@ async function updateDocImageCaption(pool, user, id, caption) {
|
||||
function mdAlt(text) {
|
||||
return String(text || '').replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
|
||||
}
|
||||
const replacement = (m, oldAlt) => newCaption ? '' : '';
|
||||
const replacement = (m, oldAlt) => newCaption ? '' : '';
|
||||
const newBody = String(article.body || '').replace(re, replacement);
|
||||
if (newBody !== article.body) {
|
||||
await pool.query('UPDATE doc_articles SET body = $1, updated_at = now() WHERE id = $2', [newBody, current.article_id]);
|
||||
|
||||
@@ -368,6 +368,9 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.group-card .name-input:focus{border-color:var(--accent)}
|
||||
.group-card .del{background:none;border:none;color:var(--muted);cursor:pointer;font-size:1.2rem;padding:4px;flex-shrink:0}
|
||||
.group-card .del:hover{color:#ef4444}
|
||||
.group-card .hide-toggle{background:none;border:none;color:var(--muted);cursor:pointer;font-size:.9rem;padding:2px;flex-shrink:0;display:inline-flex;align-items:center;justify-content:center;line-height:1}
|
||||
.group-card .hide-toggle:hover{color:var(--accent)}
|
||||
.group-card .hide-toggle svg{width:14px;height:14px;display:block}
|
||||
.group-card .group-schedule{display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:8px;align-items:start}
|
||||
.group-card .group-schedule label{font-size:.75rem;color:var(--muted);display:block;margin-bottom:4px}
|
||||
.group-card .group-schedule select,.group-card .group-schedule input[type=time]{width:100%;background:var(--bg);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:6px 8px;font-size:.8rem}
|
||||
|
||||
+17
-7
@@ -46,8 +46,8 @@
|
||||
.docs-chev svg { width: 14px; height: 14px; transition: transform .15s; }
|
||||
.docs-chev.closed svg { transform: rotate(-90deg); }
|
||||
.docs-section-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
|
||||
.docs-row-acts { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); align-items: center; gap: 2px; opacity: 0; visibility: hidden; transition: opacity .15s, visibility .15s; }
|
||||
.docs-section-row:hover .docs-row-acts, .docs-article-row:hover .docs-row-acts { opacity: 1; visibility: visible; }
|
||||
.docs-row-acts { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); display: inline-flex; align-items: center; gap: 2px; opacity: 0; visibility: hidden; transition: opacity .15s, visibility .15s; z-index: 2; pointer-events: auto; }
|
||||
.docs-section-row:hover .docs-row-acts, .docs-article-row:hover .docs-row-acts, .docs-section-row:focus-within .docs-row-acts, .docs-article-row:focus-within .docs-row-acts { opacity: 1; visibility: visible; }
|
||||
.docs-row-acts button {
|
||||
border: none;
|
||||
background: none;
|
||||
@@ -59,7 +59,7 @@
|
||||
}
|
||||
.docs-row-acts button:hover { color: var(--text); background: rgba(127,127,127,.18); }
|
||||
.docs-row-acts svg { width: 13px; height: 13px; }
|
||||
.docs-article-row { display: flex; align-items: center; gap: 4px; border-radius: 8px; }
|
||||
.docs-article-row { position: relative; display: flex; align-items: center; gap: 4px; border-radius: 8px; padding-right: 30px; }
|
||||
.docs-article-row:hover { background: rgba(127,127,127,.08); }
|
||||
.docs-article-row a {
|
||||
flex: 1;
|
||||
@@ -86,11 +86,15 @@
|
||||
.docs-article { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 26px 30px; min-height: 320px; }
|
||||
.docs-crumbs { font-size: .74rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin-bottom: 8px; }
|
||||
.docs-article h1 { font-size: 1.65rem; line-height: 1.25; margin: 0 0 10px; word-break: break-word; }
|
||||
.docs-meta { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; font-size: .78rem; color: var(--muted); margin-bottom: 14px; }
|
||||
.docs-meta { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; font-size: .78rem; color: var(--muted); margin-bottom: 14px; padding-bottom: 14px; border-bottom: 1px solid var(--border); }
|
||||
.docs-badge { display: inline-flex; align-items: center; padding: 1px 9px; border-radius: 999px; font-size: .7rem; font-weight: 600; background: rgba(245,158,11,.15); color: #d97706; }
|
||||
.docs-badge.public { background: rgba(34,197,94,.14); color: #16a34a; }
|
||||
.docs-article-actions { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 18px; padding-bottom: 16px; border-bottom: 1px solid var(--border); }
|
||||
.docs-article-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.docs-article-head h1 { margin: 0; flex: 1; min-width: 0; }
|
||||
.docs-article-actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
|
||||
.docs-article-actions:empty { display: none; }
|
||||
.docs-article-actions button { padding: 6px 8px; display: inline-flex; align-items: center; justify-content: center; }
|
||||
.docs-article-actions svg { width: 16px; height: 16px; }
|
||||
.docs-body { font-size: .95rem; line-height: 1.68; overflow-wrap: anywhere; }
|
||||
.docs-body h1, .docs-body h2, .docs-body h3, .docs-body h4 { margin: 1.4em 0 .5em; line-height: 1.3; }
|
||||
.docs-body h1 { font-size: 1.5rem; }
|
||||
@@ -199,6 +203,12 @@
|
||||
.docs-attachments-list { margin: 0; padding-left: 18px; }
|
||||
.docs-attachments-list li { margin: 0 0 4px; font-size: .9rem; }
|
||||
.docs-attach-size { color: var(--muted); font-size: .78rem; margin-left: 6px; }
|
||||
.docs-attachments-title + .docs-attachments-title { margin-top: 14px; }
|
||||
.docs-attachments-images { list-style: none; padding: 0; display: flex; flex-wrap: wrap; gap: 12px; margin: 0 0 6px; }
|
||||
.docs-attach-image { margin: 0; width: 220px; max-width: 100%; }
|
||||
.docs-attach-image img { width: 100%; border-radius: 8px; border: 1px solid var(--border); display: block; }
|
||||
.docs-attach-image .docs-caption-input { font-size: .78rem; }
|
||||
.docs-img-caption { font-size: .78rem; color: var(--muted); margin-top: 4px; font-style: italic; }
|
||||
.docs-imglib-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; max-height: 420px; overflow: auto; padding: 4px 0; }
|
||||
.docs-imglib-item { border: 1px solid var(--border); border-radius: 8px; padding: 4px; cursor: pointer; background: var(--bg); }
|
||||
.docs-imglib-item:hover { border-color: var(--accent); }
|
||||
@@ -282,10 +292,10 @@
|
||||
<button type="button" class="btn-primary ghost" id="docsFileAllBtn" title="Показать все вложения"><i data-lucide="layers"></i> Все</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="docs-files-hint" id="docsFilesHint">Файлы, прикреплённые к статье. Вставить в текст — кнопка «Вставить» вставляет ссылку в Markdown.</div>
|
||||
<div class="docs-files-hint" id="docsFilesHint">Файлы и картинки статьи. У каждой картинки есть поле подписи — подпись выводится под изображением в тексте. «Вставить» добавляет ссылку или картинку в Markdown.</div>
|
||||
<div class="docs-files-table-wrap">
|
||||
<table class="docs-files-table" id="docsFilesTable">
|
||||
<thead><tr><th>Имя</th><th>Размер</th><th>Статус</th><th>Действия</th></tr></thead>
|
||||
<thead><tr><th>Имя / подпись</th><th>Размер</th><th>Статус</th><th>Действия</th></tr></thead>
|
||||
<tbody id="docsFilesBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
<div><label>Тьютор</label><select id="groupTutorFilter"><option value="">Все тьюторы</option></select></div>
|
||||
<div><label>День</label><select id="groupDayFilter"><option value="">Все дни</option></select></div>
|
||||
<div><label> </label><button type="button" id="groupFiltersReset" style="background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:8px;padding:8px 16px;font-size:.85rem;cursor:pointer;white-space:nowrap">Сбросить</button></div>
|
||||
<div><label class="toggle"><input type="checkbox" id="groupShowHidden"><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text">Скрытые</span></label></div>
|
||||
</div>
|
||||
<div class="add-row" style="align-items:center;gap:8px">
|
||||
<input type="text" id="newGroup" placeholder="Название группы" style="flex:1;max-width:300px">
|
||||
|
||||
+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();
|
||||
}
|
||||
|
||||
+28
-5
@@ -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="Удалить">×</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]');
|
||||
|
||||
@@ -2058,6 +2058,7 @@ async function ensureBranchesTable() {
|
||||
await pool.query(`ALTER TABLE groups ADD COLUMN IF NOT EXISTS branch_id INTEGER REFERENCES branches(id) ON DELETE SET NULL`);
|
||||
await pool.query(`ALTER TABLE groups ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`);
|
||||
await pool.query(`ALTER TABLE groups ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ`);
|
||||
await pool.query(`ALTER TABLE groups ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT false`);
|
||||
}
|
||||
|
||||
async function ensureBannedIpsTable() {
|
||||
@@ -2793,6 +2794,7 @@ async function ensureUserTables() {
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at)`);
|
||||
await pool.query('ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS user_id INT REFERENCES users(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE groups ADD COLUMN IF NOT EXISTS tutor_id INT REFERENCES users(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE groups ADD COLUMN IF NOT EXISTS hidden BOOLEAN NOT NULL DEFAULT false');
|
||||
}
|
||||
|
||||
async function ensureUserNotesTable() {
|
||||
@@ -5472,7 +5474,8 @@ app.post('/api/docs/images', requireAuth, (req, res) => {
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
try {
|
||||
await convertPhoto(req.file);
|
||||
const item = await registerDocImage(pool, { path: `/uploads/${req.file.filename}`, userId: req.user.id });
|
||||
const articleId = req.body && req.body.article_id ? req.body.article_id : null;
|
||||
const item = await registerDocImage(pool, { path: `/uploads/${req.file.filename}`, userId: req.user.id, articleId });
|
||||
await logAudit(req, 'docs.image.create', { id: item.id, path: item.path });
|
||||
res.json({ item: { id: item.id, path: item.path, url: item.path } });
|
||||
} catch (e) {
|
||||
@@ -7223,8 +7226,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
}
|
||||
for (const x of ndata.groups) {
|
||||
await client.query(
|
||||
'INSERT INTO groups (id, name, created_at, day_of_week, time_start, time_end, branch_id, tutor_id, cover_path, deleted_at, purge_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)',
|
||||
[x.id, x.name, x.created_at, x.day_of_week, x.time_start, x.time_end, x.branch_id, x.tutor_id, x.cover_path, x.deleted_at || null, x.purge_at || null]
|
||||
'INSERT INTO groups (id, name, created_at, day_of_week, time_start, time_end, branch_id, tutor_id, cover_path, deleted_at, purge_at, hidden) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)',
|
||||
[x.id, x.name, x.created_at, x.day_of_week, x.time_start, x.time_end, x.branch_id, x.tutor_id, x.cover_path, x.deleted_at || null, x.purge_at || null, !!x.hidden]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.share_links) {
|
||||
@@ -7849,7 +7852,8 @@ app.get('/r/:token', (req, res) => {
|
||||
|
||||
// --- Groups CRUD ---
|
||||
app.get('/api/groups', apiLimiter, optionalAuth, async (req, res) => {
|
||||
const rows = await cacheWrap('groups:list:' + scopeKey(req.user), PUBLIC_TTL_MS, async () => {
|
||||
const includeHidden = req.query.include_hidden === '1' || req.query.include_hidden === 'true';
|
||||
const rows = await cacheWrap('groups:list:' + scopeKey(req.user) + (includeHidden ? ':h' : ''), PUBLIC_TTL_MS, async () => {
|
||||
const bw = req.user ? branchWhere(req.user, 'g') : { where: '', params: [] };
|
||||
const { rows } = await pool.query(
|
||||
`SELECT g.*,
|
||||
@@ -7861,7 +7865,7 @@ app.get('/api/groups', apiLimiter, optionalAuth, async (req, res) => {
|
||||
b.name AS branch_name
|
||||
FROM groups g
|
||||
LEFT JOIN branches b ON b.id = g.branch_id
|
||||
WHERE 1=1 AND g.deleted_at IS NULL${bw.where}
|
||||
WHERE 1=1 AND g.deleted_at IS NULL${includeHidden ? '' : ' AND g.hidden = false'}${bw.where}
|
||||
ORDER BY g.id`,
|
||||
bw.params
|
||||
);
|
||||
@@ -7875,6 +7879,7 @@ app.get('/api/groups/active', apiLimiter, async (_, res) => {
|
||||
const { rows } = await pool.query(`
|
||||
SELECT * FROM groups
|
||||
WHERE deleted_at IS NULL
|
||||
AND hidden = false
|
||||
AND day_of_week IS NOT NULL
|
||||
AND time_start IS NOT NULL
|
||||
AND time_end IS NOT NULL
|
||||
@@ -8032,6 +8037,32 @@ async function hardDeleteGroup(groupId) {
|
||||
}
|
||||
}
|
||||
|
||||
app.put('/api/groups/:id/hidden', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin') {
|
||||
if (!(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
if (!(await groupOwnedBy(pool, req.user.id, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Управлять можно только своими группами' });
|
||||
}
|
||||
}
|
||||
const hidden = req.body && req.body.hidden;
|
||||
if (typeof hidden !== 'boolean') {
|
||||
return res.status(400).json({ error: 'hidden должен быть boolean' });
|
||||
}
|
||||
const result = await pool.query(
|
||||
'UPDATE groups SET hidden = $1 WHERE id = $2 AND deleted_at IS NULL RETURNING *',
|
||||
[hidden, req.params.id]
|
||||
);
|
||||
if (result.rowCount === 0) {
|
||||
return res.status(404).json({ error: 'Группа не найдена' });
|
||||
}
|
||||
await logAudit(req, hidden ? 'group.hide' : 'group.show', { id: req.params.id });
|
||||
invalidateGroups();
|
||||
invalidateStats();
|
||||
res.json(result.rows[0]);
|
||||
});
|
||||
|
||||
app.delete('/api/groups/:id', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin') {
|
||||
if (!(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
@@ -11922,7 +11953,7 @@ async function buildPostLessonTasks(user, days) {
|
||||
const { rows: groups } = await pool.query(
|
||||
`SELECT g.id, g.name, g.branch_id, g.tutor_id, g.day_of_week, g.time_start, g.time_end
|
||||
FROM groups g
|
||||
WHERE g.deleted_at IS NULL AND g.day_of_week IS NOT NULL AND g.time_start IS NOT NULL AND g.time_end IS NOT NULL${whereGroup}`,
|
||||
WHERE g.deleted_at IS NULL AND g.hidden = false AND g.day_of_week IS NOT NULL AND g.time_start IS NOT NULL AND g.time_end IS NOT NULL${whereGroup}`,
|
||||
groupParams
|
||||
);
|
||||
if (!groups.length) return [];
|
||||
|
||||
Reference in New Issue
Block a user