Документация: разделы и статьи в docs.html

- Добавлены 12 разделов документации: Журнал, Отчёты о занятиях,
  Ученики, Группы, Обратная связь, Короткие сообщения, Чаты, Фото,
  Файлы, Ссылки, Закладки, Заметки (каждый со вступительной статьёй)
- Сид разделов в lib/docs.js (ensureDocsTables) и db/migration.sql
-doc_images добавлен в sweepOrphanedUploads и BROKEN_IMAGE_SOURCES
- Исправлен дубль docSectionIds в backup-restore.js
- Роуты /api/docs/* в server.js
- Страницы public/docs.html, public/docs-public.html, скрипты
  public/js/docs.js, public/js/docs-public.js, public/js/md.js
This commit is contained in:
dev
2026-10-23 21:33:48 +03:00
parent 4ba0f810b2
commit 97426c70af
11 changed files with 2565 additions and 6 deletions
+1
View File
@@ -63,6 +63,7 @@ function buildSidebar(active) {
{ page: 'files', label: 'Файлы', icon: 'folder' },
{ page: 'links', label: 'Ссылки', icon: 'link' },
{ page: 'bookmarks', label: 'Закладки', icon: 'bookmark' },
{ page: 'docs', label: 'Документация', icon: 'book-open-text' },
{ page: 'trash', label: 'Корзина', icon: 'trash-2' },
{ page: 'notes', label: 'Заметки', icon: 'sticky-note' },
];
+136
View File
@@ -0,0 +1,136 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Документация</title>
<style>
:root {
--bg: #f6f7f9;
--card: #ffffff;
--text: #1f2430;
--muted: #6b7280;
--border: #e3e6ec;
--accent: #2563eb;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14161b;
--card: #1b1e25;
--text: #e6e8ee;
--muted: #9aa1ad;
--border: #2b2f39;
--accent: #5b8def;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
line-height: 1.6;
}
a { color: var(--accent); }
.dp-head {
border-bottom: 1px solid var(--border);
background: var(--card);
position: sticky;
top: 0;
z-index: 10;
}
.dp-wrap { max-width: 1220px; margin: 0 auto; padding: 0 20px; }
.dp-head .dp-wrap { display: flex; align-items: center; gap: 12px; height: 58px; }
.dp-brand { font-weight: 700; font-size: 1.02rem; }
.dp-head-sub { color: var(--muted); font-size: .8rem; }
.dp-layout { display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 24px; align-items: start; padding-top: 24px; padding-bottom: 60px; }
.dp-side {
position: sticky;
top: 82px;
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 10px;
max-height: calc(100dvh - 110px);
overflow: auto;
}
.dp-tree { display: flex; flex-direction: column; gap: 1px; }
.dp-section-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 8px;
font-size: .86rem;
font-weight: 600;
cursor: pointer;
user-select: none;
}
.dp-section-row:hover { background: rgba(127,127,127,.1); }
.dp-chev { border: none; background: none; color: var(--muted); padding: 0; display: inline-flex; cursor: pointer; }
.dp-chev svg { width: 14px; height: 14px; transition: transform .15s; }
.dp-chev.closed svg { transform: rotate(-90deg); }
.dp-chev svg, .dp-section-row svg { stroke: currentColor; }
.dp-section-row .dp-folder { width: 15px; height: 15px; flex: none; color: var(--muted); }
.dp-section-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dp-article-row a {
display: block;
padding: 6px 8px;
border-radius: 8px;
color: var(--text);
text-decoration: none;
font-size: .84rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dp-article-row a:hover { background: rgba(127,127,127,.08); }
.dp-article-row a.active { background: rgba(37,99,235,.13); color: var(--accent); font-weight: 600; }
.dp-empty { color: var(--muted); font-size: .85rem; padding: 14px 8px; text-align: center; }
.dp-article { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 28px 34px; min-height: 320px; }
.dp-crumbs { font-size: .74rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin-bottom: 8px; }
.dp-article h1 { font-size: 1.65rem; line-height: 1.25; margin: 0 0 18px; word-break: break-word; }
.dp-body { font-size: .96rem; line-height: 1.68; overflow-wrap: anywhere; }
.dp-body h1, .dp-body h2, .dp-body h3, .dp-body h4 { margin: 1.4em 0 .5em; line-height: 1.3; }
.dp-body h1 { font-size: 1.5rem; }
.dp-body h2 { font-size: 1.25rem; }
.dp-body h3 { font-size: 1.08rem; }
.dp-body p { margin: 0 0 .85em; }
.dp-body ul, .dp-body ol { margin: 0 0 .9em; padding-left: 1.5em; }
.dp-body li { margin: 0 0 .25em; }
.dp-body img { max-width: 100%; border-radius: 10px; border: 1px solid var(--border); cursor: zoom-in; margin: 6px 0; }
.dp-body blockquote { margin: 0 0 1em; padding: 8px 14px; border-left: 3px solid var(--accent); background: rgba(127,127,127,.07); border-radius: 0 8px 8px 0; color: var(--muted); }
.dp-body code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .86em; background: rgba(127,127,127,.14); padding: 1px 5px; border-radius: 5px; }
.dp-body pre { background: rgba(127,127,127,.12); border-radius: 10px; padding: 12px 14px; overflow: auto; margin: 0 0 1em; }
.dp-body pre code { background: none; padding: 0; }
.dp-body hr { border: none; border-top: 1px solid var(--border); margin: 1.4em 0; }
.dp-body .md-table-wrap { overflow: auto; margin: 0 0 1em; }
.dp-body table { border-collapse: collapse; min-width: 60%; }
.dp-body th, .dp-body td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; font-size: .88rem; }
.dp-body th { background: rgba(127,127,127,.09); }
.dp-lightbox { position: fixed; inset: 0; background: rgba(0,0,0,.82); display: none; align-items: center; justify-content: center; z-index: 100; padding: 24px; }
.dp-lightbox.open { display: flex; }
.dp-lightbox img { max-width: 95vw; max-height: 92dvh; border-radius: 10px; }
@media (max-width: 900px) {
.dp-layout { grid-template-columns: 1fr; }
.dp-side { position: static; max-height: none; }
.dp-article { padding: 20px 16px; }
}
</style>
</head>
<body>
<header class="dp-head">
<div class="dp-wrap">
<div class="dp-brand">Документация</div>
<span class="dp-head-sub" id="dpHeadSub"></span>
</div>
</header>
<main class="dp-wrap dp-layout">
<aside class="dp-side"><div id="dpTree" class="dp-tree"></div></aside>
<article class="dp-article" id="dpArticle"></article>
</main>
<div class="dp-lightbox" id="dpLightbox"><img id="dpLightboxImg" alt=""></div>
<script src="js/md.js"></script>
<script src="js/docs-public.js"></script>
</body>
</html>
+285
View File
@@ -0,0 +1,285 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Документация — Админ-панель</title>
<link rel="stylesheet" href="admin.css">
<style>
.docs-wrap { display: grid; grid-template-columns: 306px minmax(0, 1fr); gap: 20px; align-items: start; }
.docs-side {
position: sticky;
top: 16px;
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 10px;
max-height: calc(100dvh - 120px);
overflow: auto;
display: flex;
flex-direction: column;
gap: 8px;
}
.docs-search { width: 100%; }
.docs-side-foot { display: flex; gap: 6px; flex-wrap: wrap; border-top: 1px solid var(--border); padding-top: 8px; margin-top: auto; }
.docs-side-foot .btn-primary { display: inline-flex; align-items: center; gap: 6px; padding: 8px 12px; font-size: .8rem; }
.docs-side-foot .btn-primary svg { width: 14px; height: 14px; }
.docs-tree { display: flex; flex-direction: column; gap: 1px; }
.docs-node { display: flex; flex-direction: column; }
.docs-section-row {
display: flex;
align-items: center;
gap: 5px;
padding: 6px 8px;
border-radius: 8px;
cursor: pointer;
font-size: .86rem;
font-weight: 600;
min-width: 0;
user-select: none;
}
.docs-section-row:hover { background: rgba(127,127,127,.1); }
.docs-section-row svg { width: 15px; height: 15px; flex: none; }
.docs-chev { border: none; background: none; color: var(--muted); padding: 0; display: inline-flex; cursor: pointer; }
.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 { margin-left: auto; display: none; align-items: center; gap: 2px; }
.docs-section-row:hover .docs-row-acts, .docs-article-row:hover .docs-row-acts { display: inline-flex; }
.docs-row-acts button {
border: none;
background: none;
color: var(--muted);
padding: 2px;
border-radius: 5px;
cursor: pointer;
display: inline-flex;
}
.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:hover { background: rgba(127,127,127,.08); }
.docs-article-row a {
flex: 1;
min-width: 0;
padding: 6px 8px;
color: var(--text);
text-decoration: none;
font-size: .84rem;
border-radius: 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.docs-article-row a.active { background: rgba(37,99,235,.14); color: var(--accent); font-weight: 600; }
.docs-article-row .docs-dot { width: 6px; height: 6px; border-radius: 50%; background: #f59e0b; flex: none; margin-left: 6px; }
.docs-empty { color: var(--muted); font-size: .85rem; padding: 14px 8px; text-align: center; }
.docs-search-results { display: flex; flex-direction: column; gap: 2px; }
.docs-search-item { padding: 8px; border-radius: 8px; cursor: pointer; border: 1px solid transparent; }
.docs-search-item:hover { border-color: var(--border); background: rgba(127,127,127,.06); }
.docs-search-item b { display: block; font-size: .84rem; margin-bottom: 2px; }
.docs-search-item span { display: block; font-size: .75rem; color: var(--muted); line-height: 1.4; }
.docs-search-item em { display: block; font-style: normal; font-size: .7rem; color: var(--accent); margin-top: 3px; }
.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-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-actions:empty { display: none; }
.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; }
.docs-body h2 { font-size: 1.25rem; }
.docs-body h3 { font-size: 1.08rem; }
.docs-body h4 { font-size: 1rem; }
.docs-body p { margin: 0 0 .85em; }
.docs-body ul, .docs-body ol { margin: 0 0 .9em; padding-left: 1.5em; }
.docs-body li { margin: 0 0 .25em; }
.docs-body img { max-width: 100%; border-radius: 10px; border: 1px solid var(--border); cursor: zoom-in; margin: 6px 0; }
.docs-body a { color: var(--accent); }
.docs-body blockquote { margin: 0 0 1em; padding: 8px 14px; border-left: 3px solid var(--accent); background: rgba(127,127,127,.07); border-radius: 0 8px 8px 0; color: var(--muted); }
.docs-body code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .86em; background: rgba(127,127,127,.14); padding: 1px 5px; border-radius: 5px; }
.docs-body pre { background: rgba(127,127,127,.12); border-radius: 10px; padding: 12px 14px; overflow: auto; margin: 0 0 1em; }
.docs-body pre code { background: none; padding: 0; }
.docs-body hr { border: none; border-top: 1px solid var(--border); margin: 1.4em 0; }
.docs-body .md-table-wrap { overflow: auto; margin: 0 0 1em; }
.docs-body table { border-collapse: collapse; min-width: 60%; }
.docs-body th, .docs-body td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; font-size: .88rem; }
.docs-body th { background: rgba(127,127,127,.09); }
.docs-editor { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 18px 20px; display: flex; flex-direction: column; gap: 12px; }
.docs-editor[hidden] { display: none; }
.docs-editor-head { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.docs-title-input {
flex: 1;
min-width: 220px;
background: var(--bg);
border: 1px solid var(--border);
color: var(--text);
border-radius: 9px;
padding: 10px 12px;
font-size: 1.1rem;
font-weight: 600;
outline: none;
font-family: inherit;
}
.docs-title-input:focus { border-color: var(--accent); }
.docs-editor-actions { display: flex; gap: 8px; }
.docs-editor-meta { display: flex; gap: 14px; align-items: center; flex-wrap: wrap; font-size: .82rem; color: var(--muted); }
.docs-editor-meta select { background: var(--bg); border: 1px solid var(--border); color: var(--text); border-radius: 8px; padding: 7px 10px; font-size: .82rem; font-family: inherit; max-width: 260px; }
.docs-editor-meta label { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
.docs-editor-meta label[hidden] { display: none; }
.docs-toolbar { display: flex; gap: 4px; flex-wrap: wrap; padding: 6px; background: var(--bg); border: 1px solid var(--border); border-radius: 10px 10px 0 0; border-bottom: none; }
.docs-toolbar button {
min-width: 30px;
height: 28px;
padding: 0 7px;
border: 1px solid transparent;
background: none;
color: var(--text);
border-radius: 6px;
cursor: pointer;
font-size: .8rem;
font-family: inherit;
display: inline-flex;
align-items: center;
justify-content: center;
}
.docs-toolbar button:hover { background: rgba(127,127,127,.16); border-color: var(--border); }
.docs-toolbar .sep { width: 1px; background: var(--border); margin: 3px 2px; }
.docs-edit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.docs-edit-area { display: flex; flex-direction: column; min-width: 0; }
#docsEditBody {
flex: 1;
min-height: 540px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 0 0 10px 10px;
color: var(--text);
padding: 14px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: .86rem;
line-height: 1.6;
resize: vertical;
outline: none;
}
#docsEditBody:focus { border-color: var(--accent); }
.docs-preview { background: var(--bg); border: 1px solid var(--border); border-radius: 10px; padding: 14px 16px; overflow: auto; max-height: 640px; }
.docs-preview .docs-body { font-size: .9rem; }
.docs-preview-empty { color: var(--muted); font-size: .82rem; }
.docs-hint { font-size: .74rem; color: var(--muted); }
.docs-drop { outline: 2px dashed var(--accent); outline-offset: -4px; }
.docs-file-input { display: none; }
.docs-modal-parent { width: 100%; }
.docs-check { display: flex; align-items: center; gap: 8px; font-size: .88rem; color: var(--text); cursor: pointer; }
@media (max-width: 1100px) { .docs-edit-grid { grid-template-columns: 1fr; } }
@media (max-width: 960px) {
.docs-wrap { grid-template-columns: 1fr; }
.docs-side { position: static; max-height: none; }
.docs-article { padding: 20px 16px; }
}
</style>
</head>
<body data-page="docs">
<div class="layout">
<div class="sidebar" id="sidebar"></div>
<div class="main">
<div class="page-head">
<h2>Документация</h2>
<p class="page-sub">Справочник по работе с системой</p>
<button type="button" class="btn-primary" id="docsNewArticleBtn"><i data-lucide="file-plus"></i> Новая статья</button>
</div>
<div class="docs-wrap">
<aside class="docs-side">
<input type="text" id="docsSearch" class="settings-input docs-search" placeholder="Поиск по документации..." autocomplete="off">
<div id="docsTree" class="docs-tree"></div>
<div class="docs-side-foot" id="docsSideFoot">
<button type="button" class="btn-primary ghost" id="docsNewSectionBtn"><i data-lucide="folder-plus"></i> Раздел</button>
</div>
</aside>
<section class="docs-content" id="docsContent"></section>
<section class="docs-editor" id="docsEditor" hidden>
<div class="docs-editor-head">
<input type="text" id="docsEditTitle" class="docs-title-input" maxlength="200" placeholder="Заголовок статьи">
<div class="docs-editor-actions">
<button type="button" class="btn-primary ghost" id="docsCancelBtn">Отмена</button>
<button type="button" class="btn-primary" id="docsSaveBtn">Сохранить</button>
</div>
</div>
<div class="docs-editor-meta">
<select id="docsEditSection"></select>
<label><input type="checkbox" id="docsEditPublished" checked> Опубликована</label>
<label id="docsEditPublicWrap"><input type="checkbox" id="docsEditPublic"> Публичная ссылка</label>
<span class="docs-hint" id="docsEditHint"></span>
</div>
<div class="docs-toolbar" id="docsToolbar">
<button type="button" data-md="h2" title="Заголовок">H2</button>
<button type="button" data-md="h3" title="Подзаголовок">H3</button>
<span class="sep"></span>
<button type="button" data-md="bold" title="Жирный"><b>B</b></button>
<button type="button" data-md="italic" title="Курсив"><i>I</i></button>
<button type="button" data-md="strike" title="Зачёркнутый"><s>S</s></button>
<button type="button" data-md="code" title="Код">&lt;/&gt;</button>
<span class="sep"></span>
<button type="button" data-md="ul" title="Маркированный список">• Список</button>
<button type="button" data-md="ol" title="Нумерованный список">1. Список</button>
<button type="button" data-md="quote" title="Цитата">❝</button>
<button type="button" data-md="table" title="Таблица">Таблица</button>
<button type="button" data-md="hr" title="Разделитель">—</button>
<span class="sep"></span>
<button type="button" data-md="link" title="Ссылка">Ссылка</button>
<button type="button" data-md="image" title="Картинка">Картинка</button>
</div>
<div class="docs-edit-grid">
<div class="docs-edit-area">
<textarea id="docsEditBody" spellcheck="true" placeholder="Текст статьи в Markdown. Картинку можно вставить из буфера обмена (Ctrl+V) или перетащить сюда."></textarea>
</div>
<div class="docs-preview"><div class="docs-body" id="docsPreview"></div></div>
</div>
<input type="file" id="docsImageFile" class="docs-file-input" accept="image/*">
</section>
</div>
</div>
</div>
<div class="modal-overlay" id="docsSectionModal">
<div class="edit-modal" style="max-width:520px">
<h3 id="docsSectionModalTitle">Новый раздел</h3>
<div class="settings-field">
<label>Название <span style="color:#ef4444">*</span></label>
<input id="docsSectionTitle" class="settings-input" maxlength="200" placeholder="Например, Журнал">
</div>
<div class="settings-field">
<label>Родительский раздел</label>
<select id="docsSectionParent" class="settings-input docs-modal-parent"></select>
</div>
<label class="docs-check"><input type="checkbox" id="docsSectionTutor"> Тьюторы могут писать статьи в этом разделе</label>
<label class="docs-check"><input type="checkbox" id="docsSectionPublic"> Показывать раздел в публичной версии</label>
<div class="card-foot">
<button type="button" class="btn-primary ghost" id="docsSectionDeleteBtn" style="display:none;color:#ef4444;border-color:rgba(239,68,68,.35)">Удалить</button>
<button type="button" class="btn-primary ghost" id="docsSectionCancel">Отмена</button>
<button type="button" class="btn-primary" id="docsSectionSave">Сохранить</button>
</div>
</div>
</div>
<div class="modal-overlay" id="imgModal">
<img id="imgModalSrc" alt="">
</div>
<div class="toast" id="toast"></div>
<script src="vendor/lucide.min.js"></script>
<script src="js/datetime.js"></script>
<script src="admin.js"></script>
<script src="js/md.js"></script>
<script src="js/docs.js"></script>
</body>
</html>
+152
View File
@@ -0,0 +1,152 @@
(function () {
const treeEl = document.getElementById('dpTree');
const articleEl = document.getElementById('dpArticle');
const headSub = document.getElementById('dpHeadSub');
const lightbox = document.getElementById('dpLightbox');
const lightboxImg = document.getElementById('dpLightboxImg');
const COLLAPSE_KEY = 'whatido.docsPublic.collapsed';
const ICON_CHEVRON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
const ICON_FOLDER = '<svg class="dp-folder" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/></svg>';
let tree = [];
let currentSlug = '';
let collapsed = new Set();
try {
const saved = JSON.parse(localStorage.getItem(COLLAPSE_KEY) || '[]');
if (Array.isArray(saved)) collapsed = new Set(saved.map(Number));
} catch (e) {}
function esc(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function saveCollapsed() {
localStorage.setItem(COLLAPSE_KEY, JSON.stringify([...collapsed]));
}
async function getJson(url) {
const res = await fetch(url);
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка загрузки');
return data;
}
function articleRow(article, depth) {
return `<div class="dp-article-row"><a href="?slug=${encodeURIComponent(article.slug)}" data-slug="${esc(article.slug)}"
style="padding-left:${26 + depth * 14}px" class="${currentSlug === article.slug ? 'active' : ''}">${esc(article.title)}</a></div>`;
}
function sectionNode(node, depth) {
const closed = collapsed.has(Number(node.id));
const hasItems = (node.children && node.children.length) || (node.articles && node.articles.length);
const chev = hasItems
? `<button type="button" class="dp-chev${closed ? ' closed' : ''}" data-toggle="${node.id}">${ICON_CHEVRON}</button>`
: '<span style="width:14px;flex:none"></span>';
const children = closed ? '' : [
...(node.children || []).map(child => sectionNode(child, depth + 1)),
...(node.articles || []).map(article => articleRow(article, depth + 1)),
].join('');
return `<div>
<div class="dp-section-row" data-section="${node.id}" style="padding-left:${8 + depth * 14}px">
${chev}${ICON_FOLDER}<span class="dp-section-title">${esc(node.title)}</span>
</div>
<div${closed ? ' hidden' : ''}>${children}</div>
</div>`;
}
function renderTree() {
if (!tree.length) {
treeEl.innerHTML = '<div class="dp-empty">Документация пока пуста</div>';
return;
}
treeEl.innerHTML = tree.map(node => sectionNode(node, 0)).join('');
}
async function open(slug, updateUrl) {
const data = await getJson('/api/docs/public/articles/' + encodeURIComponent(slug));
const article = data.item;
currentSlug = article.slug;
articleEl.innerHTML = `<div class="dp-crumbs">${esc(article.section_title || '')}</div>
<h1>${esc(article.title)}</h1>
<div class="dp-body">${WhatIDoMD.render(article.body)}</div>`;
document.title = article.title + ' — Документация';
if (headSub) headSub.textContent = article.section_title || '';
if (updateUrl !== false) history.replaceState(null, '', '?slug=' + encodeURIComponent(article.slug));
renderTree();
}
function bind() {
treeEl.addEventListener('click', e => {
const toggle = e.target.closest('[data-toggle]');
if (toggle) {
e.preventDefault();
const id = Number(toggle.dataset.toggle);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
return;
}
const link = e.target.closest('[data-slug]');
if (link) {
e.preventDefault();
open(link.dataset.slug).catch(err => { articleEl.textContent = err.message; });
return;
}
const row = e.target.closest('.dp-section-row');
if (row) {
const id = Number(row.dataset.section);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
}
});
articleEl.addEventListener('click', e => {
const img = e.target.closest('[data-img]');
if (!img) return;
e.preventDefault();
lightboxImg.src = img.dataset.img;
lightbox.classList.add('open');
});
lightbox.addEventListener('click', () => {
lightbox.classList.remove('open');
lightboxImg.removeAttribute('src');
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && lightbox.classList.contains('open')) {
lightbox.classList.remove('open');
lightboxImg.removeAttribute('src');
}
});
}
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() {
bind();
try {
const data = await getJson('/api/docs/public/tree');
tree = data.sections || [];
renderTree();
const params = new URLSearchParams(location.search);
const slug = params.get('slug') || firstSlug(tree);
if (slug) await open(slug, !params.get('slug'));
else articleEl.innerHTML = '<div class="dp-empty" style="padding:40px 0">Статьи не опубликованы</div>';
} catch (e) {
articleEl.textContent = e.message;
treeEl.innerHTML = '<div class="dp-empty">Не удалось загрузить документацию</div>';
}
}
init();
})();
+691
View File
@@ -0,0 +1,691 @@
(function () {
const el = id => document.getElementById(id);
const treeEl = el('docsTree');
const contentEl = el('docsContent');
const editorEl = el('docsEditor');
const titleEl = el('docsEditTitle');
const sectionEl = el('docsEditSection');
const publishedEl = el('docsEditPublished');
const publicEl = el('docsEditPublic');
const publicWrap = el('docsEditPublicWrap');
const bodyEl = el('docsEditBody');
const previewEl = el('docsPreview');
const hintEl = el('docsEditHint');
const searchEl = el('docsSearch');
const imageFileEl = el('docsImageFile');
const sectionModal = el('docsSectionModal');
const sectionTitleEl = el('docsSectionTitle');
const sectionParentEl = el('docsSectionParent');
const sectionTutorEl = el('docsSectionTutor');
const sectionPublicEl = el('docsSectionPublic');
const sectionDeleteBtn = el('docsSectionDeleteBtn');
const COLLAPSE_KEY = 'whatido.docs.collapsed';
let tree = [];
let current = null;
let editState = null;
let sectionEditId = null;
let collapsed = new Set();
let searchTimer = null;
let previewTimer = null;
try {
const saved = JSON.parse(localStorage.getItem(COLLAPSE_KEY) || '[]');
if (Array.isArray(saved)) collapsed = new Set(saved.map(Number));
} catch (e) {}
async function req(path, options) {
const opts = options || {};
const headers = opts.body instanceof FormData ? hdr() : hdrJson();
const res = await fetch(API + path, Object.assign({}, opts, { headers }));
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка запроса');
return data;
}
function saveCollapsed() {
localStorage.setItem(COLLAPSE_KEY, JSON.stringify([...collapsed]));
}
function sectionList() {
const out = [];
const walk = (nodes, depth) => {
for (const node of nodes) {
out.push(Object.assign({}, node, { depth }));
walk(node.children || [], depth + 1);
}
};
walk(tree, 0);
return out;
}
function findSection(id) {
return sectionList().find(s => Number(s.id) === Number(id)) || null;
}
function findSectionNode(id) {
let found = null;
const walk = nodes => {
for (const node of nodes) {
if (Number(node.id) === Number(id)) { found = node; return; }
walk(node.children || []);
if (found) return;
}
};
walk(tree);
return found;
}
function canCreateAnywhere() {
return isAdmin() || sectionList().some(s => s.can_write);
}
function updateNewArticleButton() {
const btn = el('docsNewArticleBtn');
if (btn) btn.hidden = !canCreateAnywhere();
}
async function loadTree() {
const data = await req('/api/docs/tree');
tree = data.sections || [];
updateNewArticleButton();
if (searchEl.value.trim().length >= 2) {
renderTree();
runSearch();
} else {
renderTree();
}
}
function renderIconsSafe() {
if (typeof renderIcons === 'function') renderIcons();
}
function sectionActs(node) {
const acts = [];
if (node.can_write) acts.push(`<button type="button" data-act="add-article" data-id="${node.id}" title="Новая статья"><i data-lucide="file-plus"></i></button>`);
if (isAdmin()) {
acts.push(`<button type="button" data-act="add-sub" data-id="${node.id}" title="Подраздел"><i data-lucide="folder-plus"></i></button>`);
acts.push(`<button type="button" data-act="edit-section" data-id="${node.id}" title="Изменить раздел"><i data-lucide="pencil"></i></button>`);
acts.push(`<button type="button" data-act="section-up" data-id="${node.id}" title="Выше"><i data-lucide="arrow-up"></i></button>`);
acts.push(`<button type="button" data-act="section-down" data-id="${node.id}" title="Ниже"><i data-lucide="arrow-down"></i></button>`);
}
return acts.join('');
}
function articleRow(article, depth) {
const active = current && Number(current.id) === Number(article.id);
const acts = isAdmin()
? `<button type="button" data-act="article-up" data-id="${article.id}" data-section="${article.section_id}" title="Выше"><i data-lucide="arrow-up"></i></button>
<button type="button" data-act="article-down" data-id="${article.id}" data-section="${article.section_id}" title="Ниже"><i data-lucide="arrow-down"></i></button>`
: '';
return `<div class="docs-article-row">
<a href="#a=${encodeURIComponent(article.slug)}" data-slug="${esc(article.slug)}" class="${active ? 'active' : ''}" style="padding-left:${26 + depth * 14}px" title="${esc(article.title)}">${esc(article.title)}${article.is_published ? '' : '<span class="docs-dot" title="Черновик"></span>'}</a>
<span class="docs-row-acts">${acts}</span>
</div>`;
}
function sectionNode(node, depth) {
const closed = collapsed.has(Number(node.id));
const hasItems = (node.children && node.children.length) || (node.articles && node.articles.length);
const chev = hasItems
? `<button type="button" class="docs-chev${closed ? ' closed' : ''}" data-toggle="${node.id}" aria-label="Свернуть раздел"><i data-lucide="chevron-down"></i></button>`
: '<span style="width:14px;flex:none"></span>';
const children = closed ? '' : [
...(node.children || []).map(child => sectionNode(child, depth + 1)),
...(node.articles || []).map(article => articleRow(article, depth + 1)),
].join('');
return `<div class="docs-node">
<div class="docs-section-row" data-section="${node.id}" style="padding-left:${8 + depth * 14}px">
${chev}
<i data-lucide="${closed ? 'folder' : 'folder-open'}"></i>
<span class="docs-section-title">${esc(node.title)}</span>
<span class="docs-row-acts">${sectionActs(node)}</span>
</div>
<div class="docs-children"${closed ? ' hidden' : ''}>${children}</div>
</div>`;
}
function renderTree() {
if (!tree.length) {
treeEl.innerHTML = '<div class="docs-empty">Разделов пока нет</div>';
renderIconsSafe();
return;
}
treeEl.innerHTML = tree.map(node => sectionNode(node, 0)).join('');
renderIconsSafe();
}
function renderEmpty() {
contentEl.hidden = false;
editorEl.hidden = true;
contentEl.innerHTML = `<div class="docs-article"><div class="docs-empty" style="padding:60px 16px">Выберите статью слева${canCreateAnywhere() ? ' или создайте новую' : ''}</div></div>`;
}
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>');
}
if (article.is_public) {
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="copy">Скопировать публичную ссылку</button>');
}
const meta = [];
if (article.author_name) meta.push(`<span>${esc(article.author_name)}</span>`);
if (article.updated_at) meta.push(`<span>Обновлено: ${fmtDateTime(article.updated_at)}</span>`);
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-meta">${meta.join('')}</div>
<div class="docs-article-actions">${actions.join('')}</div>
<div class="docs-body">${WhatIDoMD.render(article.body)}</div>
</article>`;
}
function renderArticle() {
if (!current) return renderEmpty();
contentEl.hidden = false;
editorEl.hidden = true;
contentEl.innerHTML = articleHtml(current);
markActive();
}
function markActive() {
treeEl.querySelectorAll('.docs-article-row a').forEach(a => {
a.classList.toggle('active', !!current && a.dataset.slug === current.slug);
});
}
async function openArticle(slug, updateHash) {
if (editState && editState.dirty && !confirm('Несохранённые изменения будут потеряны. Продолжить?')) return;
const data = await req('/api/docs/articles/' + encodeURIComponent(slug));
current = data.item;
editState = null;
if (updateHash !== false) history.replaceState(null, '', '#a=' + encodeURIComponent(current.slug));
renderArticle();
markActive();
}
function fillSectionSelect(selectedId) {
const list = sectionList().filter(s => isAdmin() || s.can_write);
sectionEl.innerHTML = list.map(s => {
const prefix = s.depth ? '\u00A0\u00A0'.repeat(s.depth) + '— ' : '';
return `<option value="${s.id}">${esc(prefix + s.title)}</option>`;
}).join('');
if (selectedId && list.some(s => Number(s.id) === Number(selectedId))) sectionEl.value = String(selectedId);
return list.length > 0;
}
function markDirty() {
if (!editState) return;
editState.dirty = true;
hintEl.textContent = 'Есть несохранённые изменения';
}
function updatePreview() {
previewEl.innerHTML = bodyEl.value.trim()
? WhatIDoMD.render(bodyEl.value)
: '<div class="docs-preview-empty">Предпросмотр появится здесь</div>';
}
function schedulePreview() {
clearTimeout(previewTimer);
previewTimer = setTimeout(updatePreview, 150);
}
function startEdit(article, presetSectionId) {
if (article && !article.can_edit) {
showToast('Нет прав на редактирование этой статьи', true);
return;
}
const list = sectionList().filter(s => isAdmin() || s.can_write);
if (!list.length) {
showToast('Нет разделов, где вам разрешено писать', true);
return;
}
editState = { id: article ? article.id : null, dirty: false };
titleEl.value = article ? article.title : '';
bodyEl.value = article ? article.body : '';
publishedEl.checked = article ? article.is_published : true;
publicEl.checked = article ? article.is_public : false;
publicWrap.hidden = !isAdmin();
const preferred = article ? article.section_id : (presetSectionId || (current && current.section_id));
fillSectionSelect(preferred);
hintEl.textContent = '';
contentEl.hidden = true;
editorEl.hidden = false;
updatePreview();
renderIconsSafe();
titleEl.focus();
titleEl.select();
}
function closeEditor() {
editorEl.hidden = true;
contentEl.hidden = false;
editState = null;
hintEl.textContent = '';
}
function cancelEdit() {
if (editState && editState.dirty && !confirm('Отменить несохранённые изменения?')) return;
closeEditor();
if (current) renderArticle(); else renderEmpty();
}
async function saveArticle() {
if (!editState) return;
const title = titleEl.value.trim();
if (!title) { showToast('Введите заголовок статьи', true); titleEl.focus(); return; }
const sectionId = parseInt(sectionEl.value, 10);
if (!Number.isInteger(sectionId) || sectionId < 1) { showToast('Выберите раздел', true); return; }
const payload = {
section_id: sectionId,
title,
body: bodyEl.value,
is_published: publishedEl.checked,
is_public: isAdmin() ? publicEl.checked : false,
};
const saveBtn = el('docsSaveBtn');
saveBtn.disabled = true;
try {
const path = editState.id ? '/api/docs/articles/' + editState.id : '/api/docs/articles';
const method = editState.id ? 'PUT' : 'POST';
const data = await req(path, { method, body: JSON.stringify(payload) });
editState.dirty = false;
closeEditor();
await loadTree();
await openArticle(data.item.slug);
showToast('Статья сохранена');
} catch (e) {
showToast(e.message, true);
} finally {
saveBtn.disabled = false;
}
}
async function deleteArticle() {
if (!current || !current.can_edit) return;
if (!confirm(`Удалить статью «${current.title}»? Действие необратимо.`)) return;
try {
await req('/api/docs/articles/' + current.id, { method: 'DELETE' });
const slug = current.slug;
current = null;
history.replaceState(null, '', location.pathname);
await loadTree();
renderEmpty();
showToast('Статья удалена');
} catch (e) {
showToast(e.message, true);
}
}
function copyPublicLink() {
if (!current) return;
const url = `${location.origin}/docs-public.html?slug=${encodeURIComponent(current.slug)}`;
const done = () => showToast('Ссылка скопирована');
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url).then(done).catch(() => prompt('Публичная ссылка', url));
} else {
prompt('Публичная ссылка', url);
}
}
function applyWrap(before, after, fallback) {
const start = bodyEl.selectionStart;
const end = bodyEl.selectionEnd;
const selected = bodyEl.value.slice(start, end);
const inner = selected || fallback || '';
bodyEl.setRangeText(before + inner + after, start, end, 'end');
bodyEl.focus();
if (!selected && inner) {
bodyEl.setSelectionRange(start + before.length, start + before.length + inner.length);
}
markDirty();
updatePreview();
}
function applyPrefix(prefix) {
const start = bodyEl.selectionStart;
const lineStart = bodyEl.value.lastIndexOf('\n', start - 1) + 1;
bodyEl.setRangeText(prefix, lineStart, lineStart, 'end');
bodyEl.focus();
markDirty();
updatePreview();
}
function insertBlock(text) {
const start = bodyEl.selectionStart;
const before = bodyEl.value.slice(0, start);
const prefix = before && !before.endsWith('\n') ? '\n' : '';
bodyEl.setRangeText(prefix + text + '\n', start, bodyEl.selectionEnd, 'end');
bodyEl.focus();
markDirty();
updatePreview();
}
function applyToolbar(kind) {
if (kind === 'bold') return applyWrap('**', '**', 'жирный текст');
if (kind === 'italic') return applyWrap('*', '*', 'курсив');
if (kind === 'strike') return applyWrap('~~', '~~', 'зачёркнутый');
if (kind === 'code') return applyWrap('`', '`', 'код');
if (kind === 'h2') return applyPrefix('## ');
if (kind === 'h3') return applyPrefix('### ');
if (kind === 'ul') return applyPrefix('- ');
if (kind === 'ol') return applyPrefix('1. ');
if (kind === 'quote') return applyPrefix('> ');
if (kind === 'hr') return insertBlock('---');
if (kind === 'link') return applyWrap('[', '](https://)', 'текст ссылки');
if (kind === 'table') return insertBlock('| Колонка | Колонка |\n| --- | --- |\n| | |');
if (kind === 'image') { imageFileEl.click(); return; }
}
async function uploadImage(file) {
if (!file || !file.type || !file.type.startsWith('image/')) {
showToast('Можно вставлять только изображения', true);
return;
}
showToast('Загрузка картинки...');
try {
const form = new FormData();
form.append('image', file);
const data = await req('/api/docs/images', { method: 'POST', body: form });
const alt = (file.name || 'картинка').replace(/\.[^.]+$/, '');
insertBlock(`![${alt}](${data.item.path})`);
showToast('Картинка добавлена');
} catch (e) {
showToast(e.message, true);
}
}
function fillParentSelect(excludeId, selectedId) {
const list = sectionList().filter(s => Number(s.id) !== Number(excludeId));
sectionParentEl.innerHTML = '<option value="">— Корень —</option>' + list.map(s => {
const prefix = s.depth ? '\u00A0\u00A0'.repeat(s.depth) + '— ' : '';
return `<option value="${s.id}">${esc(prefix + s.title)}</option>`;
}).join('');
sectionParentEl.value = selectedId ? String(selectedId) : '';
}
function openSectionModal(id, parentId) {
const section = id ? findSection(id) : null;
sectionEditId = section ? Number(section.id) : null;
el('docsSectionModalTitle').textContent = section ? 'Изменить раздел' : 'Новый раздел';
sectionTitleEl.value = section ? section.title : '';
sectionTutorEl.checked = section ? !!section.tutor_edit : false;
sectionPublicEl.checked = section ? !!section.is_public : false;
fillParentSelect(section ? section.id : null, section ? section.parent_id : (parentId || null));
sectionDeleteBtn.style.display = section ? '' : 'none';
sectionModal.classList.add('open');
sectionTitleEl.focus();
sectionTitleEl.select();
}
function closeSectionModal() {
sectionModal.classList.remove('open');
sectionEditId = null;
}
async function saveSection() {
const title = sectionTitleEl.value.trim();
if (!title) { showToast('Введите название раздела', true); sectionTitleEl.focus(); return; }
const payload = {
title,
parent_id: sectionParentEl.value ? parseInt(sectionParentEl.value, 10) : null,
tutor_edit: sectionTutorEl.checked,
is_public: sectionPublicEl.checked,
};
try {
const path = sectionEditId ? '/api/docs/sections/' + sectionEditId : '/api/docs/sections';
await req(path, { method: sectionEditId ? 'PUT' : 'POST', body: JSON.stringify(payload) });
closeSectionModal();
await loadTree();
if (current) {
try { await openArticle(current.slug); } catch (e) {}
}
showToast('Раздел сохранён');
} catch (e) {
showToast(e.message, true);
}
}
function countArticles(node) {
let total = (node.articles || []).length;
for (const child of node.children || []) total += countArticles(child);
return total;
}
async function deleteSection() {
if (!sectionEditId) return;
const node = findSectionNode(sectionEditId);
const count = node ? countArticles(node) : 0;
const warning = count ? ` Вместе с ним удалятся статьи: ${count}.` : '';
if (!confirm(`Удалить раздел «${sectionTitleEl.value.trim()}»?${warning}`)) return;
try {
const id = sectionEditId;
await req('/api/docs/sections/' + id, { method: 'DELETE' });
closeSectionModal();
await loadTree();
if (current) {
try { await openArticle(current.slug); } catch (e) { current = null; history.replaceState(null, '', location.pathname); renderEmpty(); }
}
showToast('Раздел удалён');
} catch (e) {
showToast(e.message, true);
}
}
async function moveSection(id, direction) {
const section = findSection(id);
if (!section) return;
const siblings = sectionList().filter(s => String(s.parent_id || '') === String(section.parent_id || ''));
const index = siblings.findIndex(s => Number(s.id) === Number(id));
const target = index + direction;
if (index < 0 || target < 0 || target >= siblings.length) return;
const swap = siblings[index];
siblings[index] = siblings[target];
siblings[target] = swap;
try {
await req('/api/docs/sections/reorder', {
method: 'PUT',
body: JSON.stringify({ ids: siblings.map(s => s.id) }),
});
await loadTree();
} catch (e) {
showToast(e.message, true);
}
}
async function moveArticle(id, sectionId, direction) {
const node = findSectionNode(sectionId);
if (!node) return;
const articles = (node.articles || []).slice();
const index = articles.findIndex(a => Number(a.id) === Number(id));
const target = index + direction;
if (index < 0 || target < 0 || target >= articles.length) return;
const swap = articles[index];
articles[index] = articles[target];
articles[target] = swap;
try {
await req('/api/docs/articles/reorder', {
method: 'PUT',
body: JSON.stringify({ section_id: Number(sectionId), ids: articles.map(a => a.id) }),
});
await loadTree();
} catch (e) {
showToast(e.message, true);
}
}
async function runSearch() {
const query = searchEl.value.trim();
if (query.length < 2) { renderTree(); return; }
try {
const data = await req('/api/docs/search?q=' + encodeURIComponent(query));
if (!data.items.length) {
treeEl.innerHTML = '<div class="docs-empty">Ничего не найдено</div>';
return;
}
treeEl.innerHTML = `<div class="docs-search-results">${data.items.map(item => {
const excerpt = String(item.excerpt || '').replace(/\s+/g, ' ').trim();
return `<div class="docs-search-item" data-slug="${esc(item.slug)}">
<b>${esc(item.title)}</b>
<span>${esc(excerpt)}</span>
<em>${esc(item.section_title || '')}</em>
</div>`;
}).join('')}</div>`;
} catch (e) {
showToast(e.message, true);
}
}
function bindTree() {
treeEl.addEventListener('click', e => {
const act = e.target.closest('[data-act]');
if (act) {
e.preventDefault();
e.stopPropagation();
const id = parseInt(act.dataset.id, 10);
const action = act.dataset.act;
if (action === 'add-article') return startEdit(null, id);
if (action === 'add-sub') return openSectionModal(null, id);
if (action === 'edit-section') return openSectionModal(id, null);
if (action === 'section-up') return moveSection(id, -1);
if (action === 'section-down') return moveSection(id, 1);
if (action === 'article-up') return moveArticle(id, parseInt(act.dataset.section, 10), -1);
if (action === 'article-down') return moveArticle(id, parseInt(act.dataset.section, 10), 1);
return;
}
const toggle = e.target.closest('[data-toggle]');
if (toggle) {
e.preventDefault();
e.stopPropagation();
const id = Number(toggle.dataset.toggle);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
return;
}
const link = e.target.closest('[data-slug]');
if (link) {
e.preventDefault();
openArticle(link.dataset.slug).catch(err => showToast(err.message, true));
return;
}
const row = e.target.closest('.docs-section-row');
if (row) {
const id = Number(row.dataset.section);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
}
});
}
function bindEditor() {
el('docsToolbar').addEventListener('click', e => {
const btn = e.target.closest('[data-md]');
if (!btn) return;
e.preventDefault();
applyToolbar(btn.dataset.md);
});
bodyEl.addEventListener('input', () => { markDirty(); schedulePreview(); });
bodyEl.addEventListener('dragover', e => {
if (!e.dataTransfer || ![...e.dataTransfer.types].includes('Files')) return;
e.preventDefault();
bodyEl.classList.add('docs-drop');
});
bodyEl.addEventListener('dragleave', () => bodyEl.classList.remove('docs-drop'));
bodyEl.addEventListener('drop', async e => {
const files = [...(e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : [])];
if (!files.length) return;
e.preventDefault();
bodyEl.classList.remove('docs-drop');
for (const file of files) await uploadImage(file);
});
bodyEl.addEventListener('paste', async e => {
const data = e.clipboardData;
if (!data) return;
const files = [...(data.files || [])].filter(f => f.type && f.type.startsWith('image/'));
if (!files.length) return;
e.preventDefault();
for (const file of files) await uploadImage(file);
});
[titleEl, sectionEl, publishedEl, publicEl].forEach(control => {
control.addEventListener('input', markDirty);
control.addEventListener('change', markDirty);
});
imageFileEl.addEventListener('change', async () => {
const file = imageFileEl.files && imageFileEl.files[0];
imageFileEl.value = '';
if (file) await uploadImage(file);
});
el('docsSaveBtn').addEventListener('click', saveArticle);
el('docsCancelBtn').addEventListener('click', cancelEdit);
}
function bindPage() {
el('docsNewArticleBtn').addEventListener('click', () => startEdit(null, current ? current.section_id : null));
el('docsNewSectionBtn').addEventListener('click', () => openSectionModal(null, null));
contentEl.addEventListener('click', e => {
const btn = e.target.closest('[data-doc-act]');
if (!btn) return;
const action = btn.dataset.docAct;
if (action === 'edit') startEdit(current);
if (action === 'delete') deleteArticle();
if (action === 'copy') copyPublicLink();
});
searchEl.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(runSearch, 250);
});
el('docsSectionSave').addEventListener('click', saveSection);
el('docsSectionCancel').addEventListener('click', closeSectionModal);
sectionDeleteBtn.addEventListener('click', deleteSection);
sectionModal.addEventListener('click', e => { if (e.target === sectionModal) closeSectionModal(); });
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && sectionModal.classList.contains('open')) closeSectionModal();
if ((e.ctrlKey || e.metaKey) && e.key === 's' && editState) {
e.preventDefault();
saveArticle();
}
});
window.addEventListener('beforeunload', e => {
if (editState && editState.dirty) {
e.preventDefault();
e.returnValue = '';
}
});
}
async function init() {
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
if (!isAdmin()) el('docsNewSectionBtn').hidden = true;
bindTree();
bindEditor();
bindPage();
renderIconsSafe();
try {
await loadTree();
} catch (e) {
showToast(e.message, true);
}
const hash = location.hash.replace(/^#a=/, '');
if (hash) {
try {
await openArticle(decodeURIComponent(hash), false);
} catch (e) {
renderEmpty();
}
} else {
renderEmpty();
}
renderIconsSafe();
}
init();
})();
+192
View File
@@ -0,0 +1,192 @@
(function () {
function esc(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function safeUrl(value) {
const url = String(value || '').trim();
if (/^\/uploads\/[A-Za-z0-9._-]+$/.test(url)) return url;
if (/^https?:\/\/[^\s]+$/i.test(url)) return url;
return '';
}
function thumbUrl(path) {
if (typeof window.thumbSrc === 'function') return window.thumbSrc(path);
if (path.startsWith('/uploads/')) return '/uploads/thumb/' + path.slice('/uploads/'.length);
return path;
}
function inline(raw) {
const codes = [];
let text = String(raw == null ? '' : raw).replace(/`([^`]+)`/g, (m, code) => {
codes.push(code);
return `\u0000${codes.length - 1}\u0000`;
});
text = esc(text);
text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (m, alt, src) => {
const url = safeUrl(src.replace(/&amp;/g, '&'));
if (!url) return alt;
return `<img src="${esc(thumbUrl(url))}" data-img="${esc(url)}" alt="${esc(alt)}" loading="lazy">`;
});
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => {
const url = safeUrl(href.replace(/&amp;/g, '&'));
if (!url) return label;
const external = /^https?:\/\//i.test(url);
return `<a href="${esc(url)}"${external ? ' target="_blank" rel="noopener noreferrer"' : ''}>${label}</a>`;
});
text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
text = text.replace(/__([^_]+)__/g, '<strong>$1</strong>');
text = text.replace(/~~([^~]+)~~/g, '<del>$1</del>');
text = text.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
text = text.replace(/\u0000(\d+)\u0000/g, (m, index) => `<code>${esc(codes[Number(index)])}</code>`);
return text;
}
function isBlockStart(line) {
return /^\s*$/.test(line)
|| /^```/.test(line)
|| /^#{1,4}\s+/.test(line)
|| /^\s*>\s?/.test(line)
|| /^\s*([-*+]|\d+\.)\s+/.test(line)
|| /^\s*([-*_])\1{2,}\s*$/.test(line);
}
function parseList(lines, start) {
const baseIndent = lines[start].match(/^(\s*)/)[1].length;
const ordered = /^\s*\d+\.\s+/.test(lines[start]);
let html = ordered ? '<ol>' : '<ul>';
let i = start;
while (i < lines.length) {
const line = lines[i];
const match = line.match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/);
if (!match) break;
const indent = match[1].length;
if (indent < baseIndent) break;
if (indent > baseIndent) {
const nested = parseList(lines, i);
html = html.replace(/<\/li>$/, nested.html + '</li>');
i = nested.next;
continue;
}
if (/^\s*\d+\.\s+/.test(line) !== ordered) break;
let content = match[3];
const task = content.match(/^\[( |x|X)\]\s+(.*)$/);
if (task) {
content = `<input type="checkbox" disabled${task[1].toLowerCase() === 'x' ? ' checked' : ''}> ${inline(task[2])}`;
} else {
content = inline(content);
}
html += `<li>${content}</li>`;
i++;
while (i < lines.length) {
const next = lines[i];
if (/^\s*$/.test(next)) break;
if (/^(\s*)([-*+]|\d+\.)\s+/.test(next)) break;
if (next.match(/^\s*/)[0].length <= baseIndent) break;
html = html.replace(/<\/li>$/, ' ' + inline(next.trim()) + '</li>');
i++;
}
}
html += ordered ? '</ol>' : '</ul>';
return { html, next: i };
}
function splitRow(line) {
let row = line.trim();
if (row.startsWith('|')) row = row.slice(1);
if (row.endsWith('|')) row = row.slice(0, -1);
return row.split('|').map(cell => cell.trim());
}
function renderTable(lines, start) {
const head = splitRow(lines[start]);
let i = start + 2;
const rows = [];
while (i < lines.length && lines[i].includes('|') && lines[i].trim()) {
rows.push(splitRow(lines[i]));
i++;
}
const thead = head.map(cell => `<th>${inline(cell)}</th>`).join('');
const tbody = rows.map(row => `<tr>${row.map(cell => `<td>${inline(cell)}</td>`).join('')}</tr>`).join('');
return {
html: `<div class="md-table-wrap"><table><thead><tr>${thead}</tr></thead><tbody>${tbody}</tbody></table></div>`,
next: i,
};
}
function render(markdown) {
const lines = String(markdown == null ? '' : markdown).replace(/\r\n?/g, '\n').split('\n');
const out = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (/^\s*$/.test(line)) { i++; continue; }
const fence = line.match(/^```\s*([\w-]*)\s*$/);
if (fence) {
const code = [];
i++;
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
code.push(lines[i]);
i++;
}
if (i < lines.length) i++;
out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`);
continue;
}
const heading = line.match(/^(#{1,4})\s+(.*)$/);
if (heading) {
const level = heading[1].length;
out.push(`<h${level}>${inline(heading[2])}</h${level}>`);
i++;
continue;
}
if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
out.push('<hr>');
i++;
continue;
}
if (/^\s*>\s?/.test(line)) {
const quote = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
quote.push(lines[i].replace(/^\s*>\s?/, ''));
i++;
}
out.push(`<blockquote>${render(quote.join('\n'))}</blockquote>`);
continue;
}
if (line.includes('|') && i + 1 < lines.length && /^\s*\|?[\s:|-]+\|[\s:|-]*$/.test(lines[i + 1]) && lines[i + 1].includes('-')) {
const table = renderTable(lines, i);
out.push(table.html);
i = table.next;
continue;
}
if (/^\s*([-*+]|\d+\.)\s+/.test(line)) {
const list = parseList(lines, i);
out.push(list.html);
i = list.next;
continue;
}
const paragraph = [];
while (i < lines.length && !isBlockStart(lines[i])) {
paragraph.push(lines[i]);
i++;
}
if (!paragraph.length) { i++; continue; }
out.push(`<p>${paragraph.map(inline).join('<br>')}</p>`);
}
return out.join('\n');
}
window.WhatIDoMD = { render, inline, esc, thumbUrl, safeUrl };
})();