Update documentation system: improve structure, search, and editor
This commit is contained in:
@@ -401,8 +401,9 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
|
||||
- `POST /api/docs/images` — `requireAuth`, multer `upload.single('image')`, `convertPhoto`, `registerDocImage`; файл сохраняется в `uploads/` (как обычно) и строкой в `doc_images` с `article_id = NULL`
|
||||
- `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` обязателен в `sweepOrphanedUploads()`** и в `BROKEN_IMAGE_SOURCES` — иначе sweep удалит картинки, на которые ссылается только Markdown, или они не попадут в отчёт о битых изображениях
|
||||
- **Бэкап**: `doc_sections`/`doc_articles`/`doc_images` входят в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, в `buildBackupArchive`, в `normalizeRestoreData` (`docSections`/`docArticles`/`docImages`, путь — `optUploadPath`) и в restore. Restore вставляет разделы сначала с `parent_id = NULL`, затем отдельным проходом проставляет родителей (иначе FK на ещё не вставленного родителя); у статей `author_id` и у картинок `article_id`/`uploaded_by` берутся через `(SELECT id …)`, отсутствующая ссылка даёт `NULL` (колонки nullable). `doc_images` удаляется/вставляется вместе с остальными таблицами и до `users`
|
||||
- **`doc_images.path` и `doc_files.path` обязательны в `sweepOrphanedUploads()`** и в `BROKEN_IMAGE_SOURCES` — иначе sweep удалит файлы, на которые ссылается документация, или они не попадут в отчёт о битых изображениях
|
||||
- **Бэкап**: `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` — лайтбокс открывает оригинал
|
||||
- **Страницы**:
|
||||
- `public/docs.html` + `public/js/docs.js` — дерево слева (сворачивание в `localStorage`, поиск, стрелки порядка у админа), просмотр статьи справа, инлайн-редактор с панелью Markdown и живым предпросмотром. Картинки вставляются кнопкой, Ctrl+V и drag&drop; `Ctrl/Cmd+S` сохраняет, `beforeunload` предупреждает о несохранённых правках. Статья в адресе — `#a=<slug>`
|
||||
|
||||
+6
-3
@@ -902,8 +902,11 @@ async function updateDocImageCaption(pool, user, id, caption) {
|
||||
if (article.can_edit) {
|
||||
const path = current.path;
|
||||
const escPath = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const re = new RegExp('!\\[[^\\]]*\\]\\(' + escPath + '(?:\\s+"[^"]*")?\\)', 'g');
|
||||
const replacement = () => newCaption ? '' : '';
|
||||
const re = new RegExp('!\\[([^\\]]*)\\]\\\(' + escPath + '\\)', 'g');
|
||||
function mdAlt(text) {
|
||||
return String(text || '').replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
|
||||
}
|
||||
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]);
|
||||
@@ -916,7 +919,7 @@ async function updateDocImageCaption(pool, user, id, caption) {
|
||||
|
||||
async function listAllDocImages(pool, user) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, article_id, path, uploaded_by, created_at FROM doc_images ORDER BY created_at DESC`
|
||||
`SELECT id, article_id, path, caption, uploaded_by, created_at FROM doc_images ORDER BY created_at DESC`
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
@@ -204,6 +204,7 @@
|
||||
.docs-imglib-item:hover { border-color: var(--accent); }
|
||||
.docs-imglib-item img { width: 100%; height: 90px; object-fit: cover; border-radius: 6px; display: block; }
|
||||
.docs-imglib-name { font-size: .72rem; color: var(--muted); margin-top: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.docs-imglib-caption { font-size: .68rem; color: var(--text); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.docs-caption-row { display: flex; gap: 4px; margin-top: 4px; }
|
||||
.docs-caption-input { flex: 1; font-size: .75rem; padding: 3px 6px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); }
|
||||
.docs-caption-row button { padding: 3px 8px; font-size: .75rem; }
|
||||
|
||||
+8
-5
@@ -189,7 +189,7 @@
|
||||
<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 => `<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>
|
||||
<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>` : ''}
|
||||
</article>`;
|
||||
}
|
||||
@@ -583,7 +583,8 @@
|
||||
return /\.(jpe?g|png|gif|webp|bmp|avif|ico|jfif)$/i.test(String(f.name || f.path || ''));
|
||||
}
|
||||
function insertDocFileLink(f) {
|
||||
const md = isImageFile(f) ? `` : `[${f.name}](${f.path})`;
|
||||
const alt = (f.caption || f.name || 'картинка').replace(/\\./g, '\\.');
|
||||
const md = isImageFile(f) ? `` : `[${f.name}](${f.path})`;
|
||||
insertBlock(md);
|
||||
}
|
||||
|
||||
@@ -612,9 +613,10 @@
|
||||
return;
|
||||
}
|
||||
imgLibGrid.innerHTML = items.map(it => `
|
||||
<div class="docs-imglib-item" data-img-path="${esc(it.path)}" title="${esc(it.path)}">
|
||||
<div class="docs-imglib-item" data-img-path="${esc(it.path)}" data-img-caption="${esc(it.caption || '')}" title="${esc(it.path)}">
|
||||
<img src="${esc('/uploads/thumb/' + it.path.split('/').pop())}" alt="" loading="lazy">
|
||||
<div class="docs-imglib-name">${esc(it.path.split('/').pop())}</div>
|
||||
${it.caption ? '<div class="docs-imglib-caption">' + esc(it.caption) + '</div>' : ''}
|
||||
</div>`).join('');
|
||||
} catch (e) {
|
||||
imgLibGrid.innerHTML = '<div class="docs-empty">' + esc(e.message) + '</div>';
|
||||
@@ -887,8 +889,9 @@
|
||||
if (!item) return;
|
||||
const p = item.dataset.imgPath;
|
||||
if (!p) return;
|
||||
const name = p.split('/').pop().replace(/\.[^.]+$/, '');
|
||||
insertBlock(``);
|
||||
const caption = item.dataset.imgCaption || '';
|
||||
const alt = caption || p.split("/").pop().replace(/\.[^.]+$/, "");
|
||||
insertBlock(``);
|
||||
if (imgLibModal) imgLibModal.classList.remove('open');
|
||||
showToast('Картинка вставлена');
|
||||
});
|
||||
|
||||
+3
-4
@@ -27,12 +27,11 @@
|
||||
return `\u0000${codes.length - 1}\u0000`;
|
||||
});
|
||||
text = esc(text);
|
||||
text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (m, alt, src, title) => {
|
||||
text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (m, alt, src) => {
|
||||
const url = safeUrl(src.replace(/&/g, '&'));
|
||||
if (!url) return alt;
|
||||
const t = title ? title.replace(/&/g, '&') : '';
|
||||
const img = `<img src="${esc(thumbUrl(url))}" data-img="${esc(url)}" alt="${esc(alt)}"${t ? ` title="${esc(t)}"` : ''} loading="lazy">`;
|
||||
if (t) return `<figure class="md-figure">${img}<figcaption>${esc(t)}</figcaption></figure>`;
|
||||
const img = `<img src="${esc(thumbUrl(url))}" data-img="${esc(url)}" alt="${esc(alt)}" loading="lazy">`;
|
||||
if (alt) return `<figure class="md-figure">${img}<figcaption>${esc(alt)}</figcaption></figure>`;
|
||||
return img;
|
||||
});
|
||||
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => {
|
||||
|
||||
@@ -6736,7 +6736,7 @@ function backupUploadGuard(req, res, next) {
|
||||
async function buildBackupArchive() {
|
||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
||||
try {
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, atr, sar] = await Promise.all([
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, atr, sar] = await Promise.all([
|
||||
pool.query('SELECT * FROM groups ORDER BY id'),
|
||||
pool.query('SELECT * FROM students ORDER BY id'),
|
||||
pool.query('SELECT * FROM entries ORDER BY id'),
|
||||
@@ -6771,6 +6771,7 @@ async function buildBackupArchive() {
|
||||
pool.query('SELECT * FROM doc_sections ORDER BY id'),
|
||||
pool.query('SELECT * FROM doc_articles ORDER BY id'),
|
||||
pool.query('SELECT * FROM doc_images ORDER BY id'),
|
||||
pool.query('SELECT * FROM doc_files ORDER BY id'),
|
||||
pool.query('SELECT * FROM achievement_types ORDER BY id'),
|
||||
pool.query('SELECT * FROM student_achievements ORDER BY id'),
|
||||
]);
|
||||
@@ -6793,10 +6794,12 @@ async function buildBackupArchive() {
|
||||
student_face_refs: sfr.rowCount, photo_faces: pfcs.rowCount, student_work_marks: swm.rowCount,
|
||||
achievement_types: atr.rowCount, student_achievements: sar.rowCount,
|
||||
doc_sections: ds.rowCount, doc_articles: da.rowCount, doc_images: di.rowCount,
|
||||
doc_files: df.rowCount,
|
||||
},
|
||||
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows, student_work_marks: swm.rows,
|
||||
achievement_types: atr.rows, student_achievements: sar.rows,
|
||||
doc_sections: ds.rows, doc_articles: da.rows, doc_images: di.rows,
|
||||
doc_files: df.rows,
|
||||
};
|
||||
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||
const files = await storage.downloadAll(path.join(staging, 'uploads'));
|
||||
@@ -7216,21 +7219,6 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
[x.id, x.lesson_report_id, x.text, x.source || 'manual', x.author_id, x.created_at]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.photo_jobs) {
|
||||
let ok = false;
|
||||
if (x.group_photo_id) {
|
||||
const gpx = await client.query('SELECT 1 FROM group_photos WHERE id = $1', [x.group_photo_id]);
|
||||
ok = !!gpx.rowCount;
|
||||
} else if (x.entry_id) {
|
||||
const ex = await client.query('SELECT 1 FROM entries WHERE id = $1', [x.entry_id]);
|
||||
ok = !!ex.rowCount;
|
||||
}
|
||||
if (!ok) continue;
|
||||
await client.query(
|
||||
'INSERT INTO photo_jobs (id, entry_id, group_photo_id, action, params, before_path, after_path, status, applied, attempts, error, created_at, finished_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)',
|
||||
[x.id, x.entry_id || null, x.group_photo_id || null, x.action, x.params, x.before_path, x.after_path, x.status, x.applied, x.attempts, x.error, x.created_at, x.finished_at]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.project_files) {
|
||||
await client.query(
|
||||
'INSERT INTO project_files (id, entry_id, token, path, name, detached_at, created_at, size) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
|
||||
@@ -7249,6 +7237,21 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
[x.id, x.entry_id, x.photo_path, x.caption, x.sort_order, x.face_scanned_at || null, x.face_img_width || null, x.face_img_height || null, x.created_at]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.photo_jobs) {
|
||||
let ok = false;
|
||||
if (x.group_photo_id) {
|
||||
const gpx = await client.query('SELECT 1 FROM group_photos WHERE id = $1', [x.group_photo_id]);
|
||||
ok = !!gpx.rowCount;
|
||||
} else if (x.entry_id) {
|
||||
const ex = await client.query('SELECT 1 FROM entries WHERE id = $1', [x.entry_id]);
|
||||
ok = !!ex.rowCount;
|
||||
}
|
||||
if (!ok) continue;
|
||||
await client.query(
|
||||
'INSERT INTO photo_jobs (id, entry_id, group_photo_id, action, params, before_path, after_path, status, applied, attempts, error, created_at, finished_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)',
|
||||
[x.id, x.entry_id || null, x.group_photo_id || null, x.action, x.params, x.before_path, x.after_path, x.status, x.applied, x.attempts, x.error, x.created_at, x.finished_at]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.photo_faces || [])) {
|
||||
const tbl = x.source_type === 'entry' ? 'entry_photos' : 'group_photos';
|
||||
const ex = await client.query(`SELECT 1 FROM ${tbl} WHERE id = $1`, [x.source_id]);
|
||||
|
||||
Reference in New Issue
Block a user