Этап 8: админка

- пространства: создание, значок, переименование, удаление пустых, переключатель пространства
- разделы: создание, код и цвет плашки, порядок перетаскиванием (мышь, палец, клавиатура)
- пользователи: список, роль, блокировка (сразу завершает сессии), удаление
- приглашения по одноразовой ссылке с ролью, копирование и отзыв

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
deonisii
2026-10-04 13:03:00 +03:00
co-authored by Claude Opus 5.5
parent 62a84931e7
commit 2a8c2b5110
7 changed files with 915 additions and 18 deletions
+485
View File
@@ -0,0 +1,485 @@
// Админка: пространства и разделы (порядок перетаскиванием), пользователи и роли, приглашения.
import { type FormEvent, useRef, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { type AdminUserDto, type InviteDto, PLAQUE_COLORS, type PlaqueColor, plural, ROLE_LABEL, type Role, type SectionDto, type SpaceDto } from '@kb/shared';
import { Screen } from '../components/Shell';
import { BackLink, Caps, CodeTag, Notice, ThemeButton } from '../components/ui';
import { api, ApiError, useTree } from '../lib/api';
import { useAuth } from '../lib/auth';
import { formatDate, formatRecent } from '../lib/format';
import { dropApiCache } from '../lib/offline';
import '../styles/editor.css';
import '../styles/admin.css';
const ROLES: Role[] = ['ADMIN', 'EDITOR', 'VIEWER'];
const initials = (name: string) =>
name
.split(/\s+/)
.slice(0, 2)
.map((w) => w[0]?.toUpperCase())
.join('');
/** После любой правки структуры: сбросить кеш дерева и перезапросить его. */
function useRefreshTree() {
const qc = useQueryClient();
return async () => {
await dropApiCache(['/api/tree']);
await qc.invalidateQueries({ queryKey: ['tree'] });
};
}
const errText = (e: unknown) => (e instanceof ApiError ? e.message : 'Не получилось. Проверьте связь.');
export default function AdminPage() {
const { isAdmin } = useAuth();
const { data: tree } = useTree();
const [spaceId, setSpaceId] = useState<string | null>(null);
const [error, setError] = useState('');
if (!isAdmin) {
return (
<Screen tab="home">
<div className="topline">
<BackLink to="/">Главная</BackLink>
</div>
<Notice title="Недостаточно прав">Этот экран доступен только администраторам.</Notice>
</Screen>
);
}
const spaces = tree?.spaces ?? [];
const space = spaces.find((s) => s.id === spaceId) ?? spaces[0];
return (
<Screen tab="home" wide>
<div className="topline">
<BackLink to="/">Главная</BackLink>
<ThemeButton />
</div>
<h1 className="cheat-title">Управление</h1>
{error ? (
<div className="form-error" role="alert">
{error}
</div>
) : null}
<div className="adm-grid">
<div className="adm-col">
<Spaces spaces={spaces} active={space} onPick={setSpaceId} onError={setError} counts={tree} />
{space ? <Sections key={space.id} space={space} onError={setError} /> : null}
</div>
<div className="adm-col">
<Users onError={setError} />
<Invites onError={setError} />
</div>
</div>
</Screen>
);
}
// ---------- Пространства ----------
function Spaces({
spaces,
active,
onPick,
onError,
counts,
}: {
spaces: SpaceDto[];
active: SpaceDto | undefined;
onPick: (id: string) => void;
onError: (e: string) => void;
counts: ReturnType<typeof useTree>['data'];
}) {
const refresh = useRefreshTree();
const [form, setForm] = useState<{ id: string | null; name: string; icon: string } | null>(null);
const save = async (e: FormEvent) => {
e.preventDefault();
if (!form) return;
try {
const json = { name: form.name, icon: form.icon || null };
if (form.id) await api(`/admin/spaces/${form.id}`, { method: 'PATCH', json });
else onPick((await api<SpaceDto>('/admin/spaces', { method: 'POST', json })).id);
setForm(null);
onError('');
await refresh();
} catch (err) {
onError(errText(err));
}
};
const remove = async (id: string) => {
try {
await api(`/admin/spaces/${id}`, { method: 'DELETE' });
setForm(null);
await refresh();
} catch (err) {
onError(errText(err));
}
};
return (
<section className="block">
<Caps>Пространства</Caps>
<div className="adm-spaces">
{spaces.map((s) => {
const secs = counts?.sections.filter((x) => x.spaceId === s.id) ?? [];
const arts = counts?.articles.filter((a) => secs.some((x) => x.id === a.sectionId)).length ?? 0;
return (
<div key={s.id} className={s.id === active?.id ? 'adm-space adm-space--on' : 'adm-space'}>
<button type="button" className="adm-space-pick" onClick={() => onPick(s.id)} aria-pressed={s.id === active?.id}>
<span className="space-icon">{s.icon || s.name[0]}</span>
<span className="adm-space-name">{s.name}</span>
<span className="adm-space-n">
{secs.length} {plural(secs.length, ['раздел', 'раздела', 'разделов'])} · {arts} {plural(arts, ['статья', 'статьи', 'статей'])}
</span>
</button>
<button type="button" className="adm-link" onClick={() => setForm({ id: s.id, name: s.name, icon: s.icon ?? '' })}>
Изменить
</button>
</div>
);
})}
</div>
{form ? (
<form className="adm-form" onSubmit={save}>
<label className="ed-field adm-form-grow">
<span className="ed-label">Название пространства</span>
<input className="ed-input" required autoFocus value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</label>
<label className="ed-field adm-form-short">
<span className="ed-label">Значок</span>
<input className="ed-input" maxLength={2} value={form.icon} onChange={(e) => setForm({ ...form, icon: e.target.value })} />
</label>
<div className="adm-form-actions">
<button type="submit" className="btn btn--solid">
Сохранить
</button>
<button type="button" className="btn" onClick={() => setForm(null)}>
Отмена
</button>
{form.id ? (
<button type="button" className="btn adm-danger" onClick={() => void remove(form.id!)}>
Удалить
</button>
) : null}
</div>
</form>
) : (
<button type="button" className="btn btn--dashed adm-add" onClick={() => setForm({ id: null, name: '', icon: '' })}>
+ Пространство
</button>
)}
</section>
);
}
// ---------- Разделы ----------
interface SectionForm {
id: string | null;
name: string;
code: string;
color: PlaqueColor;
}
function Sections({ space, onError }: { space: SpaceDto; onError: (e: string) => void }) {
const { data: tree } = useTree();
const refresh = useRefreshTree();
const server = (tree?.sections ?? []).filter((s) => s.spaceId === space.id);
// Пока тащим строку, показываем локальный порядок; после сохранения возвращаемся к серверному
const [local, setLocal] = useState<SectionDto[] | null>(null);
const [dragId, setDragId] = useState<string | null>(null);
const [form, setForm] = useState<SectionForm | null>(null);
const listRef = useRef<HTMLDivElement>(null);
const list = local ?? server;
const count = (id: string) => tree?.articles.filter((a) => a.sectionId === id).length ?? 0;
const saveOrder = async (items: SectionDto[]) => {
try {
await api('/admin/sections/order', { method: 'PUT', json: { ids: items.map((s) => s.id) } });
await refresh();
onError('');
} catch (err) {
onError(errText(err));
} finally {
setLocal(null);
}
};
const move = (items: SectionDto[], from: number, to: number) => {
const next = [...items];
const [x] = next.splice(from, 1);
next.splice(to, 0, x!);
return next;
};
// Перетаскивание за ручку ⋮⋮. Сделано на событиях указателя, а не на HTML5 drag-and-drop:
// тот не работает на сенсорных экранах.
const onPointerMove = (e: React.PointerEvent) => {
if (!dragId) return;
const rows = [...(listRef.current?.querySelectorAll<HTMLElement>('[data-id]') ?? [])];
const over = rows.findIndex((r) => {
const b = r.getBoundingClientRect();
return e.clientY >= b.top && e.clientY < b.bottom;
});
const from = list.findIndex((s) => s.id === dragId);
if (over >= 0 && from >= 0 && over !== from) setLocal(move(list, from, over));
};
const endDrag = () => {
if (!dragId) return;
setDragId(null);
if (local) void saveOrder(local);
};
// С клавиатуры: стрелки вверх и вниз на ручке
const onKey = (e: React.KeyboardEvent, index: number) => {
const to = e.key === 'ArrowUp' ? index - 1 : e.key === 'ArrowDown' ? index + 1 : -1;
if (to < 0 || to >= list.length) return;
e.preventDefault();
const next = move(list, index, to);
setLocal(next);
void saveOrder(next);
};
const save = async (e: FormEvent) => {
e.preventDefault();
if (!form) return;
try {
const json = { name: form.name, code: form.code, color: form.color };
if (form.id) await api(`/admin/sections/${form.id}`, { method: 'PATCH', json });
else await api('/admin/sections', { method: 'POST', json: { ...json, spaceId: space.id } });
setForm(null);
onError('');
await refresh();
} catch (err) {
onError(errText(err));
}
};
const remove = async (id: string) => {
try {
await api(`/admin/sections/${id}`, { method: 'DELETE' });
setForm(null);
onError('');
await refresh();
} catch (err) {
onError(errText(err));
}
};
return (
<section className="block">
<Caps right="перетащите за ⋮⋮ · порядок как на главной">Разделы {space.name}</Caps>
<div className="list" ref={listRef} onPointerMove={onPointerMove} onPointerUp={endDrag} onPointerCancel={endDrag}>
{list.map((s, i) => (
<div key={s.id} data-id={s.id} className={s.id === dragId ? 'adm-sec adm-sec--drag' : 'adm-sec'}>
<button
type="button"
className="adm-handle"
aria-label={`Переместить раздел «${s.name}». Стрелки вверх и вниз меняют порядок`}
onPointerDown={(e) => {
e.currentTarget.setPointerCapture(e.pointerId);
setDragId(s.id);
}}
onKeyDown={(e) => onKey(e, i)}
>
⋮⋮
</button>
<span className="adm-pos">{String(i + 1).padStart(2, '0')}</span>
<CodeTag code={s.code} />
<span className="adm-sec-name">{s.name}</span>
<span className="adm-sec-n">{count(s.id)} ст.</span>
<button type="button" className="adm-link" onClick={() => setForm({ id: s.id, name: s.name, code: s.code, color: s.color })}>
Изменить
</button>
</div>
))}
{!list.length ? <div className="sheet-empty">Разделов пока нет</div> : null}
</div>
{form ? (
<form className="adm-form" onSubmit={save}>
<label className="ed-field adm-form-grow">
<span className="ed-label">Название раздела</span>
<input className="ed-input" required autoFocus value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
</label>
<label className="ed-field adm-form-short">
<span className="ed-label">Код</span>
<input className="ed-input" required maxLength={4} value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value.toUpperCase() })} />
</label>
<div className="ed-field adm-form-wide">
<span className="ed-label">Цвет плашки</span>
<div className="adm-colors" role="radiogroup" aria-label="Цвет плашки">
{PLAQUE_COLORS.map((c) => (
<button
key={c}
type="button"
role="radio"
aria-checked={form.color === c}
aria-label={c}
className={form.color === c ? `adm-color adm-color--on plaque--${c}` : `adm-color plaque--${c}`}
onClick={() => setForm({ ...form, color: c })}
>
{form.code || 'АБ'}
</button>
))}
</div>
</div>
<div className="adm-form-actions">
<button type="submit" className="btn btn--solid">
Сохранить
</button>
<button type="button" className="btn" onClick={() => setForm(null)}>
Отмена
</button>
{form.id ? (
<button type="button" className="btn adm-danger" onClick={() => void remove(form.id!)}>
Удалить
</button>
) : null}
</div>
</form>
) : (
<button type="button" className="btn btn--dashed adm-add" onClick={() => setForm({ id: null, name: '', code: '', color: 'ink' })}>
+ Раздел
</button>
)}
</section>
);
}
// ---------- Пользователи ----------
function Users({ onError }: { onError: (e: string) => void }) {
const { user: me } = useAuth();
const qc = useQueryClient();
const users = useQuery({ queryKey: ['admin-users'], queryFn: () => api<AdminUserDto[]>('/admin/users') });
const patch = useMutation({
mutationFn: ({ id, ...json }: { id: string; role?: Role; blocked?: boolean }) => api(`/admin/users/${id}`, { method: 'PATCH', json }),
onSuccess: () => onError(''),
onError: (e) => onError(errText(e)),
onSettled: () => qc.invalidateQueries({ queryKey: ['admin-users'] }),
});
const remove = useMutation({
mutationFn: (id: string) => api(`/admin/users/${id}`, { method: 'DELETE' }),
onError: (e) => onError(errText(e)),
onSettled: () => qc.invalidateQueries({ queryKey: ['admin-users'] }),
});
const [openId, setOpenId] = useState<string | null>(null);
return (
<section className="block">
<Caps>Пользователи · {users.data?.length ?? '…'}</Caps>
<div className="list">
{users.data?.map((u) => (
<div key={u.id} className={u.blocked ? 'adm-user adm-user--blocked' : 'adm-user'}>
<div className="adm-user-row">
<span className="avatar" aria-hidden="true">
{initials(u.name)}
</span>
<button type="button" className="adm-user-main" onClick={() => setOpenId(openId === u.id ? null : u.id)} aria-expanded={openId === u.id}>
<span className="adm-user-name">
{u.name}
{u.id === me?.id ? ' (вы)' : ''}
</span>
<span className="adm-user-sub">
{u.email} · {u.blocked ? 'заблокирован' : u.lastSeenAt ? `был ${formatRecent(new Date(u.lastSeenAt).getTime())}` : 'ещё не входил'}
</span>
</button>
<div className="adm-roles" role="group" aria-label={`Роль: ${u.name}`}>
{ROLES.map((r) => (
<button
key={r}
type="button"
className={u.role === r ? 'adm-role adm-role--on' : 'adm-role'}
aria-pressed={u.role === r}
disabled={patch.isPending}
onClick={() => u.role !== r && patch.mutate({ id: u.id, role: r })}
>
{ROLE_LABEL[r]}
</button>
))}
</div>
</div>
{openId === u.id ? (
<div className="adm-user-more">
<span className="adm-user-sub">Зарегистрирован {formatDate(u.createdAt)}</span>
<button type="button" className="btn" disabled={u.id === me?.id} onClick={() => patch.mutate({ id: u.id, blocked: !u.blocked })}>
{u.blocked ? 'Разблокировать' : 'Заблокировать'}
</button>
<button type="button" className="btn adm-danger" disabled={u.id === me?.id} onClick={() => remove.mutate(u.id)}>
Удалить
</button>
</div>
) : null}
</div>
))}
</div>
</section>
);
}
// ---------- Приглашения ----------
function Invites({ onError }: { onError: (e: string) => void }) {
const qc = useQueryClient();
const invites = useQuery({ queryKey: ['admin-invites'], queryFn: () => api<InviteDto[]>('/admin/invites') });
const [role, setRole] = useState<Role>('VIEWER');
const [copied, setCopied] = useState<string | null>(null);
const latest = invites.data?.[0];
const copy = async (inv: InviteDto) => {
try {
await navigator.clipboard.writeText(inv.url);
} catch {
// Буфер обмена недоступен (не https): ссылку можно выделить и скопировать вручную
}
setCopied(inv.id);
setTimeout(() => setCopied((c) => (c === inv.id ? null : c)), 1800);
};
const create = async () => {
try {
const inv = await api<InviteDto>('/admin/invites', { method: 'POST', json: { role } });
await qc.invalidateQueries({ queryKey: ['admin-invites'] });
await copy(inv);
onError('');
} catch (err) {
onError(errText(err));
}
};
const revoke = async (id: string) => {
await api(`/admin/invites/${id}`, { method: 'DELETE' }).catch((e) => onError(errText(e)));
await qc.invalidateQueries({ queryKey: ['admin-invites'] });
};
return (
<section className="adm-invite">
<div className="adm-invite-title">Приглашение по ссылке</div>
<div className="adm-invite-text">Ссылка одноразовая и действует 7 дней. Новый пользователь получит роль «{ROLE_LABEL[role]}».</div>
<div className="adm-roles adm-roles--wide" role="group" aria-label="Роль для приглашения">
{ROLES.map((r) => (
<button key={r} type="button" className={role === r ? 'adm-role adm-role--on' : 'adm-role'} aria-pressed={role === r} onClick={() => setRole(r)}>
{ROLE_LABEL[r]}
</button>
))}
</div>
<button type="button" className="btn btn--solid btn--lg" onClick={() => void create()}>
{copied && copied === latest?.id ? 'Ссылка скопирована' : 'Пригласить по ссылке'}
</button>
{invites.data?.map((inv) => (
<div key={inv.id} className="adm-invite-row">
<input className="adm-invite-url" readOnly value={inv.url} aria-label="Ссылка-приглашение" onFocus={(e) => e.target.select()} />
<span className="adm-invite-meta">
{ROLE_LABEL[inv.role]} · до {formatDate(inv.expiresAt)}
</span>
<button type="button" className="btn" onClick={() => void copy(inv)}>
{copied === inv.id ? 'Скопировано' : 'Скопировать'}
</button>
<button type="button" className="btn adm-danger" onClick={() => void revoke(inv.id)}>
Отозвать
</button>
</div>
))}
</section>
);
}
+7 -1
View File
@@ -1,7 +1,7 @@
import { useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { plural } from '@kb/shared';
import { Screen } from '../components/Shell';
import { Screen, SpacePicker } from '../components/Shell';
import { UserMenu } from '../components/UserMenu';
import { Caps, CodeTag, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
import { useArticle } from '../lib/api';
@@ -58,6 +58,12 @@ export function HomePage() {
<ThemeButton />
</header>
{nav.spaces.length > 1 ? (
<div className="home-space">
<SpacePicker />
</div>
) : null}
{/* Поле на главной только открывает экран поиска: печатать удобнее там, где сразу видны результаты */}
<div className="home-search">
<label className="search-field">