- редактор по макету: 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>
138 lines
6.2 KiB
TypeScript
138 lines
6.2 KiB
TypeScript
// Поле ввода 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" />;
|
|
});
|