Этап 7: редактор статей
- редактор по макету: CodeMirror 6 + живой предпросмотр тем же рендером @kb/md - тулбар вставки блоков, автодополнение [[ по названиям, подсветка битых ссылок - загрузка картинок: перетаскивание, Ctrl+V, выбор файла → сразу вставляется  - свойства: название, раздел, теги, оборудование, шифр, видимость, закрепление - черновик отдельно от опубликованного текста, автосохранение каждые 10 с - публикация с новой версией, история версий с diff и откатом - прикрепление исходников (PDF/DOC/DOCX/XLS/XLSX/DWG) с проверкой содержимого - API редактирования только для EDITOR и ADMIN; API админки (пользователи, приглашения, пространства, разделы) только для ADMIN - обновление данных на странице, когда service worker получил новую версию - scripts/check-roles.mjs: проверка прав гостя, читателя и редактора на сервере Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
90ad495901
commit
8920c16e6f
@@ -10,10 +10,17 @@
|
||||
"typecheck": "tsc -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@fontsource-variable/onest": "^5.3.1",
|
||||
"@kb/md": "workspace:^",
|
||||
"@kb/shared": "workspace:^",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
"@tanstack/react-query": "^5.104.1",
|
||||
"codemirror": "^6.0.2",
|
||||
"qrcode-generator": "^2.0.4",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
|
||||
@@ -17,6 +17,8 @@ import { SectionPage } from './pages/Section';
|
||||
|
||||
// Редко нужные экраны грузятся отдельными файлами, чтобы не замедлять чтение статей
|
||||
const PrintPage = lazy(() => import('./pages/Print'));
|
||||
const EditorPage = lazy(() => import('./pages/Editor'));
|
||||
const NewArticlePage = lazy(() => import('./pages/NewArticle'));
|
||||
|
||||
function NotFound() {
|
||||
return (
|
||||
@@ -78,6 +80,8 @@ export function App() {
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="/invite/:token" element={<InvitePage />} />
|
||||
<Route path="/edit/:slug" element={<EditorPage />} />
|
||||
<Route path="/new" element={<NewArticlePage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// Поле ввода Markdown на CodeMirror 6: подсветка, автодополнение [[ссылок]], вставка картинок.
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
|
||||
import { autocompletion, type CompletionContext, type CompletionResult } from '@codemirror/autocomplete';
|
||||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
|
||||
import { EditorState } from '@codemirror/state';
|
||||
import { EditorView, placeholder } from '@codemirror/view';
|
||||
import { tags } from '@lezer/highlight';
|
||||
import { minimalSetup } from 'codemirror';
|
||||
|
||||
export interface MdEditorHandle {
|
||||
/** Вставить текст на место курсора. */
|
||||
insert: (text: string) => void;
|
||||
focus: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
/** Статьи для автодополнения после «[[». */
|
||||
links: { slug: string; title: string }[];
|
||||
/** Пользователь вставил или перетащил файлы-картинки. */
|
||||
onImages: (files: File[]) => void;
|
||||
}
|
||||
|
||||
// Цвета берём из токенов темы, поэтому редактор сам перекрашивается при смене темы
|
||||
const theme = EditorView.theme({
|
||||
'&': { height: '100%', fontSize: 'var(--fs-15)', color: 'var(--ink)', backgroundColor: 'var(--sf)' },
|
||||
'.cm-scroller': { fontFamily: 'var(--font)', lineHeight: '1.65', overflow: 'auto' },
|
||||
'.cm-content': { padding: 'var(--sp-8) var(--sp-10)', caretColor: 'var(--ink)' },
|
||||
'&.cm-focused': { outline: 'none' },
|
||||
'.cm-cursor': { borderLeftColor: 'var(--ink)' },
|
||||
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground': { backgroundColor: 'var(--sf2) !important' },
|
||||
'.cm-placeholder': { color: 'var(--ink2)' },
|
||||
'.cm-tooltip': { border: 'var(--bw) solid var(--ln)', borderRadius: 'var(--r-md)', backgroundColor: 'var(--sf)', color: 'var(--ink)', overflow: 'hidden' },
|
||||
'.cm-tooltip-autocomplete ul li': { padding: 'var(--sp-4) var(--sp-6) !important', fontFamily: 'var(--font)' },
|
||||
'.cm-tooltip-autocomplete ul li[aria-selected]': { backgroundColor: 'var(--ink)', color: 'var(--bg)' },
|
||||
'.cm-completionDetail': { marginLeft: 'var(--sp-4)', opacity: '0.7', fontStyle: 'normal' },
|
||||
});
|
||||
|
||||
const highlight = HighlightStyle.define([
|
||||
{ tag: tags.heading, fontWeight: '700', color: 'var(--acc)' },
|
||||
{ tag: tags.strong, fontWeight: '700', color: 'var(--acc)' },
|
||||
{ tag: tags.emphasis, fontStyle: 'italic' },
|
||||
{ tag: [tags.link, tags.url], color: 'var(--blu)' },
|
||||
{ tag: [tags.processingInstruction, tags.meta, tags.punctuation], color: 'var(--ink2)' },
|
||||
]);
|
||||
|
||||
export const MdEditor = forwardRef<MdEditorHandle, Props>(function MdEditor({ value, onChange, links, onImages }, ref) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const view = useRef<EditorView | null>(null);
|
||||
// Свежие значения пропсов для обработчиков CodeMirror (он создаётся один раз)
|
||||
const latest = useRef({ onChange, links, onImages });
|
||||
useEffect(() => {
|
||||
latest.current = { onChange, links, onImages };
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Автодополнение: после «[[» показываем статьи, поиск по названию и по slug
|
||||
const wikiComplete = (ctx: CompletionContext): CompletionResult | null => {
|
||||
const m = ctx.matchBefore(/\[\[[^\]\n]*$/);
|
||||
if (!m) return null;
|
||||
const typed = m.text.slice(2).toLowerCase();
|
||||
return {
|
||||
from: m.from + 2,
|
||||
filter: false,
|
||||
options: latest.current.links
|
||||
.filter((l) => l.slug.includes(typed) || l.title.toLowerCase().includes(typed))
|
||||
.slice(0, 30)
|
||||
.map((l) => ({ label: l.title, detail: l.slug, apply: `${l.slug}]]` })),
|
||||
};
|
||||
};
|
||||
|
||||
const images = (list: FileList | null | undefined) => [...(list ?? [])].filter((f) => f.type.startsWith('image/'));
|
||||
|
||||
const v = new EditorView({
|
||||
parent: host.current!,
|
||||
state: EditorState.create({
|
||||
doc: value,
|
||||
extensions: [
|
||||
minimalSetup,
|
||||
markdown(),
|
||||
syntaxHighlighting(highlight),
|
||||
EditorView.lineWrapping,
|
||||
autocompletion({ override: [wikiComplete], icons: false }),
|
||||
placeholder('Текст статьи в Markdown. Блоки вставляются кнопками сверху.'),
|
||||
theme,
|
||||
EditorView.contentAttributes.of({ spellcheck: 'false', 'aria-label': 'Текст статьи (Markdown)' }),
|
||||
EditorView.updateListener.of((u) => {
|
||||
if (u.docChanged) latest.current.onChange(u.state.doc.toString());
|
||||
}),
|
||||
EditorView.domEventHandlers({
|
||||
paste(e) {
|
||||
const files = images(e.clipboardData?.files);
|
||||
if (!files.length) return false;
|
||||
e.preventDefault();
|
||||
latest.current.onImages(files);
|
||||
return true;
|
||||
},
|
||||
drop(e) {
|
||||
const files = images(e.dataTransfer?.files);
|
||||
if (!files.length) return false;
|
||||
e.preventDefault();
|
||||
latest.current.onImages(files);
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
});
|
||||
view.current = v;
|
||||
return () => v.destroy();
|
||||
// Редактор создаётся один раз; внешние изменения value подхватывает эффект ниже
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Текст поменяли снаружи (загрузили статью, вернули старую версию): заменяем содержимое
|
||||
useEffect(() => {
|
||||
const v = view.current;
|
||||
if (v && v.state.doc.toString() !== value) {
|
||||
v.dispatch({ changes: { from: 0, to: v.state.doc.length, insert: value } });
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
insert(text) {
|
||||
const v = view.current;
|
||||
if (!v) return;
|
||||
const { from, to } = v.state.selection.main;
|
||||
v.dispatch({ changes: { from, to, insert: text }, selection: { anchor: from + text.length }, scrollIntoView: true });
|
||||
v.focus();
|
||||
},
|
||||
focus: () => view.current?.focus(),
|
||||
}));
|
||||
|
||||
return <div ref={host} className="cm-host" />;
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// Построчное сравнение двух текстов для «Истории версий».
|
||||
// Алгоритм: наибольшая общая подпоследовательность строк (LCS), классическая таблица.
|
||||
|
||||
export interface DiffLine {
|
||||
type: 'same' | 'add' | 'del' | 'skip';
|
||||
text: string;
|
||||
}
|
||||
|
||||
export function diffLines(before: string, after: string): DiffLine[] {
|
||||
const a = before.split('\n');
|
||||
const b = after.split('\n');
|
||||
// lcs[i][j] = длина общей части для a[i..] и b[j..]
|
||||
const lcs: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
|
||||
for (let i = a.length - 1; i >= 0; i--) {
|
||||
for (let j = b.length - 1; j >= 0; j--) {
|
||||
lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
|
||||
}
|
||||
}
|
||||
|
||||
const out: DiffLine[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < a.length && j < b.length) {
|
||||
if (a[i] === b[j]) {
|
||||
out.push({ type: 'same', text: a[i]! });
|
||||
i++;
|
||||
j++;
|
||||
} else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) {
|
||||
out.push({ type: 'del', text: a[i++]! });
|
||||
} else {
|
||||
out.push({ type: 'add', text: b[j++]! });
|
||||
}
|
||||
}
|
||||
while (i < a.length) out.push({ type: 'del', text: a[i++]! });
|
||||
while (j < b.length) out.push({ type: 'add', text: b[j++]! });
|
||||
return collapse(out);
|
||||
}
|
||||
|
||||
/** Длинные одинаковые участки сворачиваем: оставляем по 2 строки вокруг изменений. */
|
||||
function collapse(lines: DiffLine[]): DiffLine[] {
|
||||
const keep = new Array<boolean>(lines.length).fill(false);
|
||||
lines.forEach((l, idx) => {
|
||||
if (l.type === 'same') return;
|
||||
for (let k = Math.max(0, idx - 2); k <= Math.min(lines.length - 1, idx + 2); k++) keep[k] = true;
|
||||
});
|
||||
const out: DiffLine[] = [];
|
||||
let skipped = 0;
|
||||
lines.forEach((l, idx) => {
|
||||
if (keep[idx]) {
|
||||
if (skipped) out.push({ type: 'skip', text: `… ${skipped} строк без изменений …` });
|
||||
skipped = 0;
|
||||
out.push(l);
|
||||
} else skipped++;
|
||||
});
|
||||
if (skipped && out.length) out.push({ type: 'skip', text: `… ${skipped} строк без изменений …` });
|
||||
return out;
|
||||
}
|
||||
@@ -157,3 +157,14 @@ export async function clearPrivateCaches() {
|
||||
if (!cacheSupported()) return;
|
||||
await Promise.all([caches.delete(API_CACHE), caches.delete(IMG_CACHE)]).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Убрать из кеша устаревшие ответы API (после публикации статьи или правок в админке). */
|
||||
export async function dropApiCache(paths: string[]) {
|
||||
if (!cacheSupported()) return;
|
||||
try {
|
||||
const cache = await caches.open(API_CACHE);
|
||||
await Promise.all(paths.map((p) => cache.delete(p)));
|
||||
} catch {
|
||||
// кеш недоступен: не страшно, он обновится сам при следующем открытии
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export function useNav() {
|
||||
error,
|
||||
space: data?.spaces[0] ?? null,
|
||||
sections: views,
|
||||
/** Все разделы, включая пустые (для редактора и админки). */
|
||||
allSections: sections,
|
||||
articles,
|
||||
pinned,
|
||||
article: (slug: string) => bySlug.get(slug),
|
||||
|
||||
@@ -28,6 +28,20 @@ const queryClient = new QueryClient({
|
||||
// Service worker: кеширует интерфейс и открытые статьи, сам обновляется при выходе новой версии
|
||||
registerSW({ immediate: true });
|
||||
|
||||
// Service worker сначала отдаёт сохранённую версию, а свежую получает в фоне.
|
||||
// Когда она отличается, он пишет в этот канал, и мы перезапрашиваем данные (уже из обновлённого кеша).
|
||||
if ('BroadcastChannel' in window) {
|
||||
new BroadcastChannel('kb-api-updates').onmessage = (e: MessageEvent) => {
|
||||
const url = (e.data as { payload?: { updatedURL?: string } })?.payload?.updatedURL;
|
||||
if (!url) return;
|
||||
const path = new URL(url).pathname;
|
||||
if (path === '/api/tree') void queryClient.invalidateQueries({ queryKey: ['tree'] });
|
||||
else if (path.startsWith('/api/articles/')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['article', decodeURIComponent(path.slice('/api/articles/'.length))] });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
|
||||
@@ -63,7 +63,7 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
const listItem = nav.article(slug);
|
||||
const section = nav.sectionOf(art ?? listItem);
|
||||
|
||||
const { user } = useAuth();
|
||||
const { user, isEditor } = useAuth();
|
||||
const artSlug = art?.slug;
|
||||
useEffect(() => {
|
||||
if (!artSlug) return;
|
||||
@@ -204,15 +204,28 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
<IconPrint size={20} />
|
||||
Печать / PDF
|
||||
</button>
|
||||
{isEditor ? (
|
||||
<Link className="btn btn--solid" to={`/edit/${slug}`}>
|
||||
Редактировать
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="art-layout">
|
||||
<article className="art">
|
||||
<div className="topline art-topline">
|
||||
<BackLink to={backTo}>{section?.name ?? 'Главная'}</BackLink>
|
||||
{cached ? <OfflinePill /> : null}
|
||||
<span className="topline-right">
|
||||
{cached ? <OfflinePill /> : null}
|
||||
{isEditor ? (
|
||||
<Link className="btn" to={`/edit/${slug}`}>
|
||||
Править
|
||||
</Link>
|
||||
) : null}
|
||||
</span>
|
||||
</div>
|
||||
<div className="art-over">{section?.name}</div>
|
||||
{art.status === 'DRAFT' ? <span className="badge-draft">Черновик: читатели не видят</span> : null}
|
||||
<h1 className="art-title">{art.title}</h1>
|
||||
{art.summary ? <p className="art-summary">{art.summary}</p> : null}
|
||||
<div className="art-meta-mobile">{meta}</div>
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
// Редактор статьи: Markdown слева, живой предпросмотр (тем же рендером, что на сервере), свойства справа.
|
||||
// На телефоне упрощённый вид с переключателем Текст / Просмотр / Свойства.
|
||||
|
||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { renderMarkdown } from '@kb/md';
|
||||
import type { AttachmentDto, RevisionDto, Visibility } from '@kb/shared';
|
||||
import { ArticleBody } from '../components/ArticleBody';
|
||||
import { MdEditor, type MdEditorHandle } from '../components/MdEditor';
|
||||
import { Notice, Sheet, Skeleton } from '../components/ui';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { diffLines } from '../lib/diff';
|
||||
import { fileExt, formatBytes, formatDate } from '../lib/format';
|
||||
import { dropApiCache } from '../lib/offline';
|
||||
import { useNav } from '../lib/tree';
|
||||
import '../styles/editor.css';
|
||||
|
||||
interface Meta {
|
||||
title: string;
|
||||
summary: string;
|
||||
sectionId: string;
|
||||
tags: string[];
|
||||
equipment: string[];
|
||||
docCode: string | null;
|
||||
pinned: boolean;
|
||||
visibility: Visibility;
|
||||
order: number;
|
||||
}
|
||||
|
||||
interface EditData {
|
||||
id: string;
|
||||
slug: string;
|
||||
status: 'DRAFT' | 'PUBLISHED';
|
||||
version: number;
|
||||
updatedAt: string;
|
||||
md: string;
|
||||
meta: Meta;
|
||||
draft: { md: string; meta: Meta | null; at: string | null } | null;
|
||||
attachments: AttachmentDto[];
|
||||
}
|
||||
|
||||
// Заготовки блоков (из макета). dot: цвет метки на кнопке.
|
||||
const SNIPPETS: { label: string; dot: string; text: string }[] = [
|
||||
{ label: 'Главное', dot: 'var(--brand)', text: '\n:::keyfacts\n- Параметр: **значение**\n:::\n' },
|
||||
{ label: 'Запрет', dot: 'var(--redS)', text: '\n:::danger\nЧто запрещено: **коротко и конкретно**.\n:::\n' },
|
||||
{ label: 'Внимание', dot: 'var(--ambln)', text: '\n:::warning\nНа что обратить **внимание**.\n:::\n' },
|
||||
{ label: 'Совет', dot: 'var(--grnS)', text: '\n:::tip\nСовет или исключение из правила.\n:::\n' },
|
||||
{ label: 'Справка', dot: 'var(--blu)', text: '\n:::info\nУточнить у заказчика: …\n:::\n' },
|
||||
{ label: 'Чек-лист', dot: 'var(--ink2)', text: '\n- [ ] Пункт\n- [ ] Пункт\n' },
|
||||
{ label: 'Таблица', dot: 'var(--ink2)', text: '\n| Что | Значение |\n|---|---|\n| Параметр | **1 м** |\n' },
|
||||
];
|
||||
|
||||
const AUTOSAVE_MS = 10_000;
|
||||
const hhmm = (d: Date | string) => new Date(d).toTimeString().slice(0, 5);
|
||||
|
||||
/** Поле с «чипами»: теги, оборудование. Enter или запятая с пробелом добавляет значение. */
|
||||
function ChipsInput({ label, values, onChange, placeholder }: { label: string; values: string[]; onChange: (v: string[]) => void; placeholder: string }) {
|
||||
const [text, setText] = useState('');
|
||||
const add = () => {
|
||||
const v = text.trim();
|
||||
if (v && !values.includes(v)) onChange([...values, v]);
|
||||
setText('');
|
||||
};
|
||||
return (
|
||||
<div className="ed-field">
|
||||
<span className="ed-label">{label}</span>
|
||||
<div className="ed-chips">
|
||||
{values.map((v) => (
|
||||
<button key={v} type="button" className="ed-chip" onClick={() => onChange(values.filter((x) => x !== v))} aria-label={`Убрать: ${v}`}>
|
||||
{v} ✕
|
||||
</button>
|
||||
))}
|
||||
<input
|
||||
className="ed-chips-input"
|
||||
value={text}
|
||||
placeholder={placeholder}
|
||||
aria-label={label}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onBlur={add}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
add();
|
||||
} else if (e.key === 'Backspace' && !text && values.length) onChange(values.slice(0, -1));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EditorPage() {
|
||||
const { slug = '' } = useParams();
|
||||
const { isEditor } = useAuth();
|
||||
const { data, error, isLoading } = useQuery({
|
||||
queryKey: ['edit', slug],
|
||||
queryFn: () => api<EditData>(`/edit/articles/${encodeURIComponent(slug)}`),
|
||||
enabled: isEditor,
|
||||
staleTime: Infinity,
|
||||
gcTime: 0,
|
||||
});
|
||||
|
||||
if (!isEditor) {
|
||||
return (
|
||||
<div className="ed-wrap">
|
||||
<Notice title="Недостаточно прав">Редактировать статьи могут редакторы и администраторы.</Notice>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="ed-wrap">
|
||||
{isLoading ? <Skeleton /> : <Notice title="Не удалось открыть статью" tone="error">{error instanceof ApiError ? error.message : 'Проверьте связь.'}</Notice>}
|
||||
<Link to="/" className="btn">
|
||||
На главную
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// key: при переходе к другой статье состояние редактора создаётся заново
|
||||
return <Editor key={data.id} data={data} />;
|
||||
}
|
||||
|
||||
function Editor({ data }: { data: EditData }) {
|
||||
const nav = useNav();
|
||||
const qc = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const editor = useRef<MdEditorHandle>(null);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const docInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Если есть несохранённая публикация (черновик), продолжаем с неё
|
||||
const [md, setMd] = useState(data.draft?.md ?? data.md);
|
||||
const [meta, setMeta] = useState<Meta>(data.draft?.meta ?? data.meta);
|
||||
const [attachments, setAttachments] = useState(data.attachments);
|
||||
const [version, setVersion] = useState(data.version);
|
||||
const [published, setPublished] = useState(data.status === 'PUBLISHED');
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [tab, setTab] = useState<'text' | 'preview' | 'meta'>('text');
|
||||
const [status, setStatus] = useState(
|
||||
data.draft?.at ? `Черновик · сохранён ${hhmm(data.draft.at)}` : published ? `Опубликовано · v${data.version} · ${formatDate(data.updatedAt)}` : 'Черновик',
|
||||
);
|
||||
const [errorText, setErrorText] = useState('');
|
||||
const [historyOpen, setHistoryOpen] = useState(false);
|
||||
|
||||
const change = (next: string) => {
|
||||
setMd(next);
|
||||
setDirty(true);
|
||||
setStatus('Черновик · есть несохранённые изменения');
|
||||
};
|
||||
const changeMeta = (patch: Partial<Meta>) => {
|
||||
setMeta((m) => ({ ...m, ...patch }));
|
||||
setDirty(true);
|
||||
setStatus('Черновик · есть несохранённые изменения');
|
||||
};
|
||||
|
||||
// Предпросмотр: тот же рендер, что на сервере. useDeferredValue не даёт ему тормозить набор текста.
|
||||
const deferred = useDeferredValue(md);
|
||||
const preview = useMemo(
|
||||
() => renderMarkdown(deferred, { resolveLink: (s) => nav.article(s)?.title }),
|
||||
[deferred, nav],
|
||||
);
|
||||
const links = useMemo(() => nav.articles.map((a) => ({ slug: a.slug, title: a.title })), [nav.articles]);
|
||||
|
||||
// Актуальные значения для таймера автосохранения
|
||||
const state = useRef({ md, meta, dirty, busy });
|
||||
useEffect(() => {
|
||||
state.current = { md, meta, dirty, busy };
|
||||
});
|
||||
|
||||
const saveDraft = useCallback(
|
||||
async (silent = false) => {
|
||||
const s = state.current;
|
||||
if (silent && (!s.dirty || s.busy)) return;
|
||||
try {
|
||||
const r = await api<{ at: string }>(`/edit/articles/${data.id}/draft`, { method: 'PUT', json: { md: s.md, meta: s.meta } });
|
||||
// Пока шёл запрос, текст могли поменять: тогда «несохранённое» остаётся
|
||||
if (state.current.md === s.md && state.current.meta === s.meta) setDirty(false);
|
||||
setStatus(`Черновик сохранён · ${hhmm(r.at)}`);
|
||||
setErrorText('');
|
||||
} catch (e) {
|
||||
if (!silent) setErrorText(e instanceof ApiError ? e.message : 'Не удалось сохранить');
|
||||
setStatus('Не сохранено: нет связи. Текст остаётся в этом окне');
|
||||
}
|
||||
},
|
||||
[data.id],
|
||||
);
|
||||
|
||||
// Автосохранение черновика каждые 10 секунд
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => void saveDraft(true), AUTOSAVE_MS);
|
||||
return () => clearInterval(id);
|
||||
}, [saveDraft]);
|
||||
|
||||
// Предупреждение при закрытии вкладки с несохранённым текстом
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
|
||||
window.addEventListener('beforeunload', warn);
|
||||
return () => window.removeEventListener('beforeunload', warn);
|
||||
}, [dirty]);
|
||||
|
||||
const publish = async () => {
|
||||
setBusy(true);
|
||||
setErrorText('');
|
||||
try {
|
||||
const r = await api<{ version: number; at: string }>(`/edit/articles/${data.id}/publish`, { method: 'POST', json: { md, meta } });
|
||||
setVersion(r.version);
|
||||
setPublished(true);
|
||||
setDirty(false);
|
||||
setStatus(`Опубликовано · v${r.version} · ${hhmm(r.at)}`);
|
||||
// Читатели должны увидеть новую версию, а не сохранённую в кеше
|
||||
await dropApiCache(['/api/tree', `/api/articles/${data.slug}`]);
|
||||
await qc.invalidateQueries({ predicate: (q) => ['tree', 'article', 'search', 'revisions'].includes(String(q.queryKey[0])) });
|
||||
} catch (e) {
|
||||
setErrorText(e instanceof ApiError ? e.message : 'Не удалось опубликовать');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const unpublish = async () => {
|
||||
await api(`/edit/articles/${data.id}/unpublish`, { method: 'POST' });
|
||||
setPublished(false);
|
||||
setStatus('Снято с публикации · читатели статью не видят');
|
||||
await dropApiCache(['/api/tree', `/api/articles/${data.slug}`]);
|
||||
await qc.invalidateQueries({ queryKey: ['tree'] });
|
||||
};
|
||||
|
||||
// Картинки: загружаем по очереди и сразу вставляем  на место курсора
|
||||
const uploadImages = async (files: File[]) => {
|
||||
let done = 0;
|
||||
setStatus(`Загрузка фото: 0 из ${files.length}…`);
|
||||
for (const file of files) {
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('articleId', data.id);
|
||||
const r = await api<{ url: string }>('/edit/images', { method: 'POST', body: form });
|
||||
editor.current?.insert(`\n\n`);
|
||||
done++;
|
||||
setStatus(`Загрузка фото: ${done} из ${files.length}…`);
|
||||
} catch (e) {
|
||||
setErrorText(`${file.name}: ${e instanceof ApiError ? e.message : 'не загрузилось'}`);
|
||||
}
|
||||
}
|
||||
if (done) setStatus(`Фото добавлено · ${done} шт.`);
|
||||
};
|
||||
|
||||
const uploadDoc = async (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const att = await api<AttachmentDto>(`/edit/articles/${data.id}/attachments`, { method: 'POST', body: form });
|
||||
setAttachments((list) => [...list.filter((a) => a.id !== att.id), att]);
|
||||
setErrorText('');
|
||||
} catch (e) {
|
||||
setErrorText(e instanceof ApiError ? e.message : 'Файл не загрузился');
|
||||
}
|
||||
};
|
||||
|
||||
const removeDoc = async (id: string) => {
|
||||
await api(`/edit/attachments/${id}`, { method: 'DELETE' });
|
||||
setAttachments((list) => list.filter((a) => a.id !== id));
|
||||
};
|
||||
|
||||
const back = () => navigate(published ? `/a/${data.slug}` : '/');
|
||||
|
||||
const toolbar = (
|
||||
<div className="ed-toolbar" role="toolbar" aria-label="Вставить блок">
|
||||
{SNIPPETS.map((s) => (
|
||||
<button key={s.label} type="button" className="ed-tool" onClick={() => editor.current?.insert(s.text)}>
|
||||
<span className="ed-tool-dot" style={{ background: s.dot }} aria-hidden="true" />
|
||||
{s.label}
|
||||
</button>
|
||||
))}
|
||||
<button type="button" className="ed-tool" onClick={() => fileInput.current?.click()}>
|
||||
<span className="ed-tool-dot" style={{ background: 'var(--ink2)' }} aria-hidden="true" />
|
||||
Фото
|
||||
</button>
|
||||
<button type="button" className="ed-tool" onClick={() => editor.current?.insert('[[')}>
|
||||
<span className="ed-tool-dot" style={{ background: 'var(--ink2)' }} aria-hidden="true" />
|
||||
Ссылка на статью
|
||||
</button>
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
void uploadImages([...(e.target.files ?? [])]);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
const metaPanel = (
|
||||
<div className="ed-meta">
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Название</span>
|
||||
<input className="ed-input" value={meta.title} onChange={(e) => changeMeta({ title: e.target.value })} />
|
||||
</label>
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Краткое описание</span>
|
||||
<textarea className="ed-input ed-input--area" rows={3} value={meta.summary} onChange={(e) => changeMeta({ summary: e.target.value })} />
|
||||
</label>
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Раздел</span>
|
||||
<select className="ed-input" value={meta.sectionId} onChange={(e) => changeMeta({ sectionId: e.target.value })}>
|
||||
{nav.allSections.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<ChipsInput label="Теги" values={meta.tags} onChange={(tags) => changeMeta({ tags })} placeholder="+ тег" />
|
||||
<ChipsInput label="Оборудование" values={meta.equipment} onChange={(equipment) => changeMeta({ equipment })} placeholder="+ модель" />
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Шифр документа</span>
|
||||
<input className="ed-input" value={meta.docCode ?? ''} onChange={(e) => changeMeta({ docCode: e.target.value || null })} />
|
||||
</label>
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Кто видит</span>
|
||||
<select className="ed-input" value={meta.visibility} onChange={(e) => changeMeta({ visibility: e.target.value as Visibility })}>
|
||||
<option value="PRIVATE">Только вошедшие пользователи</option>
|
||||
<option value="PUBLIC">Все, у кого есть ссылка (без входа)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="ed-check">
|
||||
<input type="checkbox" checked={meta.pinned} onChange={(e) => changeMeta({ pinned: e.target.checked })} />
|
||||
Закрепить как шпаргалку
|
||||
</label>
|
||||
|
||||
<div className="ed-field">
|
||||
<span className="ed-label">Исходный файл</span>
|
||||
{attachments.map((a) => (
|
||||
<div key={a.id} className="ed-file">
|
||||
<span className="ed-file-ext">{fileExt(a.filename)}</span>
|
||||
<a className="ed-file-name" href={a.url} download={a.filename}>
|
||||
{a.filename} · {formatBytes(a.size)}
|
||||
</a>
|
||||
<button type="button" className="ed-file-del" onClick={() => void removeDoc(a.id)} aria-label={`Удалить ${a.filename}`}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" className="btn btn--dashed" onClick={() => docInput.current?.click()}>
|
||||
+ Прикрепить PDF или DOCX
|
||||
</button>
|
||||
<input
|
||||
ref={docInput}
|
||||
type="file"
|
||||
accept=".pdf,.doc,.docx,.xls,.xlsx,.dwg"
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
void uploadDoc(e.target.files?.[0]);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="ed-drop"
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
void uploadImages([...e.dataTransfer.files].filter((f) => f.type.startsWith('image/')));
|
||||
}}
|
||||
>
|
||||
<span className="ed-drop-title">Перетащите фото сюда</span>
|
||||
<span className="ed-drop-text">или Ctrl+V в тексте · JPG, PNG до 15 МБ</span>
|
||||
</div>
|
||||
|
||||
<button type="button" className="btn" onClick={() => setHistoryOpen(true)}>
|
||||
История версий · v{version}
|
||||
</button>
|
||||
{published ? (
|
||||
<button type="button" className="btn" onClick={() => void unpublish()}>
|
||||
Снять с публикации
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="ed">
|
||||
<header className="ed-head">
|
||||
<button type="button" className="ed-back" onClick={back} aria-label="Назад">
|
||||
‹
|
||||
</button>
|
||||
<div className="ed-head-text">
|
||||
<div className="ed-title">{meta.title || 'Без названия'}</div>
|
||||
<div className="ed-status" role="status">
|
||||
{status}
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="btn ed-only-desk" onClick={() => setHistoryOpen(true)}>
|
||||
История версий
|
||||
</button>
|
||||
<button type="button" className="btn btn--outline ed-only-desk" onClick={() => void saveDraft()} disabled={busy}>
|
||||
Черновик
|
||||
</button>
|
||||
<button type="button" className="btn btn--solid ed-only-desk" onClick={() => void publish()} disabled={busy}>
|
||||
Опубликовать
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="ed-tabs segmented segmented--3" role="group" aria-label="Вид">
|
||||
{(
|
||||
[
|
||||
['text', 'Текст'],
|
||||
['preview', 'Просмотр'],
|
||||
['meta', 'Свойства'],
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
<button key={id} type="button" className={tab === id ? 'seg seg--on' : 'seg'} aria-pressed={tab === id} onClick={() => setTab(id)}>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{toolbar}
|
||||
|
||||
{errorText ? (
|
||||
<div className="form-error ed-error" role="alert">
|
||||
{errorText}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={`ed-cols ed-cols--${tab}`}>
|
||||
<section className="ed-col ed-col--text">
|
||||
<div className="ed-col-head">MARKDOWN</div>
|
||||
<MdEditor ref={editor} value={md} onChange={change} links={links} onImages={(files) => void uploadImages(files)} />
|
||||
</section>
|
||||
<section className="ed-col ed-col--preview">
|
||||
<div className="ed-col-head">ПРЕДПРОСМОТР · 390 PX</div>
|
||||
<div className="ed-preview">
|
||||
<div className="ed-preview-phone">
|
||||
{preview.brokenLinks.length ? (
|
||||
<div className="form-error">Битые ссылки: {preview.brokenLinks.map((s) => `[[${s}]]`).join(', ')}</div>
|
||||
) : null}
|
||||
<ArticleBody html={preview.html} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section className="ed-col ed-col--meta">{metaPanel}</section>
|
||||
</div>
|
||||
|
||||
<footer className="ed-foot">
|
||||
<button type="button" className="btn btn--outline btn--lg" onClick={() => void saveDraft()} disabled={busy}>
|
||||
Черновик
|
||||
</button>
|
||||
<button type="button" className="btn btn--solid btn--lg" onClick={() => void publish()} disabled={busy}>
|
||||
Опубликовать
|
||||
</button>
|
||||
</footer>
|
||||
|
||||
{historyOpen ? (
|
||||
<History
|
||||
articleId={data.id}
|
||||
current={md}
|
||||
onClose={() => setHistoryOpen(false)}
|
||||
onRestore={(text) => {
|
||||
change(text);
|
||||
setHistoryOpen(false);
|
||||
setStatus('Возвращена старая версия · нажмите «Опубликовать», чтобы она стала текущей');
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** История версий: список, сравнение выбранной версии с текстом в редакторе, откат. */
|
||||
function History({ articleId, current, onClose, onRestore }: { articleId: string; current: string; onClose: () => void; onRestore: (md: string) => void }) {
|
||||
const [picked, setPicked] = useState<number | null>(null);
|
||||
const list = useQuery({ queryKey: ['revisions', articleId], queryFn: () => api<RevisionDto[]>(`/edit/articles/${articleId}/revisions`) });
|
||||
const rev = useQuery({
|
||||
queryKey: ['revision', articleId, picked],
|
||||
queryFn: () => api<{ version: number; md: string }>(`/edit/articles/${articleId}/revisions/${picked}`),
|
||||
enabled: picked !== null,
|
||||
});
|
||||
// Что изменится в редакторе, если вернуть выбранную версию: было «сейчас», станет «версия»
|
||||
const diff = useMemo(() => (rev.data ? diffLines(current, rev.data.md) : []), [rev.data, current]);
|
||||
const changed = diff.some((l) => l.type === 'add' || l.type === 'del');
|
||||
|
||||
return (
|
||||
<Sheet title="История версий" subtitle={picked ? `Сравнение: текст в редакторе → v${picked}` : 'Выберите версию, чтобы сравнить'} onClose={onClose}>
|
||||
<div className="sheet-scroll">
|
||||
{list.isLoading ? <div className="sheet-empty">Загрузка…</div> : null}
|
||||
{list.data?.length === 0 ? <div className="sheet-empty">Опубликованных версий пока нет</div> : null}
|
||||
{list.data?.map((r) => (
|
||||
<button key={r.id} type="button" className={picked === r.version ? 'rev-row rev-row--on' : 'rev-row'} onClick={() => setPicked(r.version)}>
|
||||
<span className="rev-v">v{r.version}</span>
|
||||
<span className="rev-main">{[r.comment, r.authorName].filter(Boolean).join(' · ') || 'Без комментария'}</span>
|
||||
<span className="rev-date">{formatDate(r.createdAt)}</span>
|
||||
</button>
|
||||
))}
|
||||
{picked !== null && rev.data ? (
|
||||
<div className="rev-diff">
|
||||
{changed ? (
|
||||
<pre className="diff">
|
||||
{diff.map((l, i) => (
|
||||
<span key={i} className={`diff-line diff-line--${l.type}`}>
|
||||
{l.type === 'add' ? '+ ' : l.type === 'del' ? '− ' : ' '}
|
||||
{l.text || ' '}
|
||||
{'\n'}
|
||||
</span>
|
||||
))}
|
||||
</pre>
|
||||
) : (
|
||||
<div className="sheet-empty">Эта версия совпадает с текстом в редакторе</div>
|
||||
)}
|
||||
<button type="button" className="btn btn--solid btn--lg btn--block" disabled={!changed} onClick={() => onRestore(rev.data.md)}>
|
||||
Вернуть версию v{picked}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { type FormEvent, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { BackLink, Notice } from '../components/ui';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { useNav } from '../lib/tree';
|
||||
import '../styles/editor.css';
|
||||
|
||||
// Новая статья: спрашиваем название и раздел, создаём черновик и открываем редактор.
|
||||
export default function NewArticlePage() {
|
||||
const nav = useNav();
|
||||
const { isEditor } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [title, setTitle] = useState('');
|
||||
const [sectionId, setSectionId] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const section = sectionId || nav.allSections[0]?.id || '';
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const r = await api<{ slug: string }>('/edit/articles', { method: 'POST', json: { title, sectionId: section } });
|
||||
navigate(`/edit/${r.slug}`, { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось создать статью');
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
</div>
|
||||
<h1 className="cheat-title">Новая статья</h1>
|
||||
{!isEditor ? (
|
||||
<Notice title="Недостаточно прав">Создавать статьи могут редакторы и администраторы.</Notice>
|
||||
) : (
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<label className="field">
|
||||
<span className="field-label">Название</span>
|
||||
<input className="field-input field-input--box" required minLength={2} autoFocus value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">Раздел</span>
|
||||
<select className="field-input field-input--box" value={section} onChange={(e) => setSectionId(e.target.value)}>
|
||||
{nav.allSections.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy || !section}>
|
||||
Создать черновик
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -52,6 +52,7 @@ export function SectionPage() {
|
||||
<div className="art-card-head">
|
||||
<span className="art-card-n">{num2(i + 1)}</span>
|
||||
<span className="art-card-title">{nav.short(a)}</span>
|
||||
{a.status === 'DRAFT' ? <span className="badge-draft">Черновик</span> : null}
|
||||
</div>
|
||||
{a.summary ? <div className="art-card-text">{a.summary}</div> : null}
|
||||
{a.tags.length ? (
|
||||
|
||||
@@ -2466,3 +2466,8 @@ mark {
|
||||
font-size: var(--fs-12);
|
||||
font-weight: 700;
|
||||
}
|
||||
.topline-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
/* Редактор статьи (макеты 06 и D6) и общие поля форм админки. */
|
||||
|
||||
.ed-wrap {
|
||||
max-width: 560px;
|
||||
margin: 0 auto;
|
||||
padding: var(--sp-12) var(--sp-8);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-8);
|
||||
}
|
||||
|
||||
.ed {
|
||||
height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.ed-head {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
padding: calc(var(--sp-1) + env(safe-area-inset-top)) var(--sp-8) var(--sp-1) var(--sp-4);
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-back {
|
||||
flex: none;
|
||||
min-width: var(--tap-sm);
|
||||
min-height: var(--tap);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-24);
|
||||
cursor: pointer;
|
||||
}
|
||||
.ed-head-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.ed-title {
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.ed-status {
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.ed-only-desk {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.ed-tabs {
|
||||
flex: none;
|
||||
margin: var(--sp-4) var(--sp-8) 0;
|
||||
}
|
||||
.ed-tabs + .ed-toolbar {
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-head,
|
||||
.ed-tabs {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ed-toolbar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: var(--sp-3);
|
||||
overflow-x: auto;
|
||||
padding: var(--sp-5) var(--sp-8);
|
||||
border-bottom: var(--bw) solid var(--ln);
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.ed-toolbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.ed-tool {
|
||||
flex: none;
|
||||
height: var(--tap);
|
||||
padding: 0 var(--sp-7);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--sf);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
.ed-tool-dot {
|
||||
flex: none;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.ed-error {
|
||||
flex: none;
|
||||
margin: var(--sp-4) var(--sp-8) 0;
|
||||
}
|
||||
|
||||
.ed-cols {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
}
|
||||
.ed-col {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
}
|
||||
.ed-cols--text .ed-col--text,
|
||||
.ed-cols--preview .ed-col--preview,
|
||||
.ed-cols--meta .ed-col--meta {
|
||||
display: flex;
|
||||
}
|
||||
.ed-col--text,
|
||||
.ed-col--meta {
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-col-head {
|
||||
display: none;
|
||||
}
|
||||
.cm-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.cm-host .cm-editor {
|
||||
height: 100%;
|
||||
}
|
||||
.ed-preview {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-8);
|
||||
}
|
||||
.ed-preview-phone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-8);
|
||||
}
|
||||
.ed-preview .kb-link--broken {
|
||||
border-color: var(--redS);
|
||||
background: var(--redbg);
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.ed-meta {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-9);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-7);
|
||||
}
|
||||
.ed-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.ed-label {
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
}
|
||||
.ed-input {
|
||||
width: 100%;
|
||||
min-height: var(--tap-sm);
|
||||
padding: var(--sp-4) var(--sp-6);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--sf);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.ed-input--area {
|
||||
resize: vertical;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.ed-chips {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
flex-wrap: wrap;
|
||||
padding: var(--sp-3);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
}
|
||||
.ed-chip {
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
border: 0;
|
||||
border-radius: var(--r-tag);
|
||||
background: var(--sf2);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-13);
|
||||
cursor: pointer;
|
||||
min-height: 32px;
|
||||
}
|
||||
.ed-chips-input {
|
||||
flex: 1;
|
||||
min-width: 90px;
|
||||
min-height: 32px;
|
||||
padding: 0 var(--sp-4);
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-13);
|
||||
}
|
||||
.ed-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
min-height: var(--tap-sm);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
}
|
||||
.ed-check input {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
accent-color: var(--grnS);
|
||||
}
|
||||
.ed-file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
padding: var(--sp-5) var(--sp-6);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
}
|
||||
.ed-file-ext {
|
||||
flex: none;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
padding: var(--sp-3) var(--sp-2);
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-plaque);
|
||||
}
|
||||
.ed-file-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: var(--fs-13);
|
||||
word-break: break-all;
|
||||
}
|
||||
.ed-file-del {
|
||||
flex: none;
|
||||
width: var(--tap-sm);
|
||||
height: var(--tap-sm);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.ed-drop {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--sp-2);
|
||||
min-height: 96px;
|
||||
padding: var(--sp-6);
|
||||
border: 2px dashed var(--ln);
|
||||
border-radius: var(--r-btn);
|
||||
text-align: center;
|
||||
}
|
||||
.ed-drop-title {
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 700;
|
||||
}
|
||||
.ed-drop-text {
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
}
|
||||
|
||||
.ed-foot {
|
||||
flex: none;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1.4fr;
|
||||
gap: var(--sp-4);
|
||||
padding: var(--sp-5) var(--sp-8) calc(var(--sp-8) + env(safe-area-inset-bottom));
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: var(--sf);
|
||||
}
|
||||
|
||||
/* История версий */
|
||||
.rev-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
width: 100%;
|
||||
min-height: var(--tap);
|
||||
padding: var(--sp-5) var(--sp-9);
|
||||
border: 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.rev-row--on {
|
||||
background: var(--sf2);
|
||||
box-shadow: inset 4px 0 0 var(--hl);
|
||||
}
|
||||
.rev-v {
|
||||
flex: none;
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
}
|
||||
.rev-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.rev-date {
|
||||
flex: none;
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.rev-diff {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-6);
|
||||
padding: var(--sp-6) var(--sp-9) 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
}
|
||||
.diff {
|
||||
margin: 0;
|
||||
max-height: 40dvh;
|
||||
overflow: auto;
|
||||
padding: var(--sp-5);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg);
|
||||
font-family: var(--font);
|
||||
font-size: var(--fs-13);
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.diff-line {
|
||||
display: block;
|
||||
}
|
||||
.diff-line--add {
|
||||
background: var(--grnbg);
|
||||
color: var(--grn);
|
||||
}
|
||||
.diff-line--del {
|
||||
background: var(--redbg);
|
||||
color: var(--red);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.diff-line--skip {
|
||||
color: var(--ink2);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ---------- Компьютер: три колонки ---------- */
|
||||
@media (min-width: 1024px) {
|
||||
.ed-head {
|
||||
gap: var(--sp-6);
|
||||
height: 68px;
|
||||
padding: 0 var(--sp-12);
|
||||
border-bottom: var(--bw) solid var(--ln);
|
||||
}
|
||||
.ed-title {
|
||||
font-size: var(--fs-18);
|
||||
}
|
||||
.ed-status {
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.ed-only-desk {
|
||||
display: inline-flex;
|
||||
}
|
||||
.ed-tabs,
|
||||
.ed-foot {
|
||||
display: none;
|
||||
}
|
||||
.ed-toolbar {
|
||||
flex-wrap: wrap;
|
||||
padding: var(--sp-5) var(--sp-12);
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-tool {
|
||||
height: var(--h-chip);
|
||||
padding: 0 var(--sp-6);
|
||||
border-radius: 9px;
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.ed-error {
|
||||
margin: var(--sp-4) var(--sp-12) 0;
|
||||
}
|
||||
.ed-cols {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 320px;
|
||||
}
|
||||
.ed-col,
|
||||
.ed-cols .ed-col {
|
||||
display: flex;
|
||||
border-right: var(--bw) solid var(--ln);
|
||||
}
|
||||
.ed-col--meta {
|
||||
border-right: 0;
|
||||
}
|
||||
.ed-col-head {
|
||||
display: block;
|
||||
flex: none;
|
||||
padding: var(--sp-4) var(--sp-10);
|
||||
font-size: var(--fs-12);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
border-bottom: var(--bw) solid var(--ln);
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-preview {
|
||||
padding: var(--sp-10);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
.ed-preview-phone {
|
||||
width: 390px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.ed .sheet-wrap {
|
||||
left: 0;
|
||||
}
|
||||
.ed .scrim {
|
||||
left: 0;
|
||||
}
|
||||
.ed .sheet {
|
||||
width: 640px;
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,8 @@ export default defineConfig({
|
||||
options: {
|
||||
cacheName: 'kb-api',
|
||||
cacheableResponse: { statuses: [200] },
|
||||
// Если в фоне пришла новая версия, сообщаем странице: она перерисует данные (см. main.tsx)
|
||||
broadcastUpdate: { channelName: 'kb-api-updates', options: { headersToCheck: ['etag'] } },
|
||||
expiration: { maxEntries: 600 },
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user