From 773e092253a90a920815af6e8a5cce03669797b8 Mon Sep 17 00:00:00 2001 From: dev Date: Sun, 1 Nov 2026 14:44:05 +0300 Subject: [PATCH] Update documentation system: improve structure, search, and editor --- AGENTS.md | 5 +++-- lib/docs.js | 9 ++++++--- public/docs.html | 1 + public/js/docs.js | 13 ++++++++----- public/js/md.js | 7 +++---- server.js | 35 +++++++++++++++++++---------------- 6 files changed, 40 insertions(+), 30 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6e5c209..b415487 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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/`); `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/` — хранимый 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=` diff --git a/lib/docs.js b/lib/docs.js index ccbedcc..01a60ba 100644 --- a/lib/docs.js +++ b/lib/docs.js @@ -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 ? '![' + newCaption + '](' + path + ')' : '![](' + path + ')'; + const re = new RegExp('!\\[([^\\]]*)\\]\\\(' + escPath + '\\)', 'g'); + function mdAlt(text) { + return String(text || '').replace(/\\/g, '\\\\').replace(/\]/g, '\\]'); + } + const replacement = (m, oldAlt) => newCaption ? '![' + mdAlt(newCaption) + '](' + path + ')' : '![' + mdAlt(oldAlt) + '](' + path + ')'; 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; } diff --git a/public/docs.html b/public/docs.html index 0e4ffb8..8c9f476 100644 --- a/public/docs.html +++ b/public/docs.html @@ -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; } diff --git a/public/js/docs.js b/public/js/docs.js index c4a0cf6..9b1a795 100644 --- a/public/js/docs.js +++ b/public/js/docs.js @@ -189,7 +189,7 @@
${WhatIDoMD.render(article.body)}
${(article.files && article.files.length) ? `
Вложения
-
    ${article.files.map(f => `
  • ${esc(f.name)} ${fmtBytes(f.size_bytes)}
  • `).join('')}
+
    ${article.files.map(f => { const isImg = f._kind === 'image'; const captionInput = isImg ? `
    ` : ''; return `
  • ${esc(f.name)}${captionInput} ${fmtBytes(f.size_bytes)}
  • `; }).join('')}
` : ''} `; } @@ -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})` : `[${f.name}](${f.path})`; + const alt = (f.caption || f.name || 'картинка').replace(/\\./g, '\\.'); + const md = isImageFile(f) ? `![${alt}](${f.path})` : `[${f.name}](${f.path})`; insertBlock(md); } @@ -612,9 +613,10 @@ return; } imgLibGrid.innerHTML = items.map(it => ` -
+
${esc(it.path.split('/').pop())}
+ ${it.caption ? '
' + esc(it.caption) + '
' : ''}
`).join(''); } catch (e) { imgLibGrid.innerHTML = '
' + esc(e.message) + '
'; @@ -887,8 +889,9 @@ if (!item) return; const p = item.dataset.imgPath; if (!p) return; - const name = p.split('/').pop().replace(/\.[^.]+$/, ''); - insertBlock(`![${name}](${p})`); + const caption = item.dataset.imgCaption || ''; + const alt = caption || p.split("/").pop().replace(/\.[^.]+$/, ""); + insertBlock(`![${alt}](${p})`); if (imgLibModal) imgLibModal.classList.remove('open'); showToast('Картинка вставлена'); }); diff --git a/public/js/md.js b/public/js/md.js index e8c21e8..6f06cab 100644 --- a/public/js/md.js +++ b/public/js/md.js @@ -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 = `${esc(alt)}`; - if (t) return `
${img}
${esc(t)}
`; + const img = `${esc(alt)}`; + if (alt) return `
${img}
${esc(alt)}
`; return img; }); text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => { diff --git a/server.js b/server.js index 30c4a2c..888cfd7 100644 --- a/server.js +++ b/server.js @@ -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]);