Этап 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
+2
View File
@@ -19,6 +19,7 @@ import { SectionPage } from './pages/Section';
const PrintPage = lazy(() => import('./pages/Print')); const PrintPage = lazy(() => import('./pages/Print'));
const EditorPage = lazy(() => import('./pages/Editor')); const EditorPage = lazy(() => import('./pages/Editor'));
const NewArticlePage = lazy(() => import('./pages/NewArticle')); const NewArticlePage = lazy(() => import('./pages/NewArticle'));
const AdminPage = lazy(() => import('./pages/Admin'));
function NotFound() { function NotFound() {
return ( return (
@@ -82,6 +83,7 @@ export function App() {
<Route path="/invite/:token" element={<InvitePage />} /> <Route path="/invite/:token" element={<InvitePage />} />
<Route path="/edit/:slug" element={<EditorPage />} /> <Route path="/edit/:slug" element={<EditorPage />} />
<Route path="/new" element={<NewArticlePage />} /> <Route path="/new" element={<NewArticlePage />} />
<Route path="/admin" element={<AdminPage />} />
<Route path="*" element={<NotFound />} /> <Route path="*" element={<NotFound />} />
</Routes> </Routes>
</Suspense> </Suspense>
+28 -10
View File
@@ -2,7 +2,8 @@
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import { Link, NavLink, useLocation } from 'react-router-dom'; import { Link, NavLink, useLocation } from 'react-router-dom';
import { THEME_LABEL, THEME_ORDER, useTheme } from '../lib/theme'; import { THEME_LABEL, THEME_ORDER, useTheme } from '../lib/theme';
import { articleHref, useNav } from '../lib/tree'; import { setStored } from '../lib/store';
import { articleHref, SPACE_KEY, useNav } from '../lib/tree';
import { IconDoc, IconHome, IconSearch, IconStar } from './Icons'; import { IconDoc, IconHome, IconSearch, IconStar } from './Icons';
import { OfflineBanner } from './Offline'; import { OfflineBanner } from './Offline';
import { CodeTag } from './ui'; import { CodeTag } from './ui';
@@ -35,6 +36,31 @@ export function TabBar({ active }: { active: Tab }) {
); );
} }
/** Переключатель пространства. Если пространство одно, это просто подпись. */
export function SpacePicker() {
const nav = useNav();
if (!nav.space) return null;
return (
<label className="space-pick">
<span className="space-pick-icon">{nav.space.icon || nav.space.name[0]}</span>
<span className="space-pick-text">
<span className="space-pick-label">Пространство</span>
{nav.spaces.length > 1 ? (
<select className="space-pick-select" value={nav.space.id} onChange={(e) => setStored(SPACE_KEY, e.target.value)}>
{nav.spaces.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
) : (
<span className="space-pick-name">{nav.space.name}</span>
)}
</span>
</label>
);
}
export function Sidebar() { export function Sidebar() {
const nav = useNav(); const nav = useNav();
const { theme, setTheme } = useTheme(); const { theme, setTheme } = useTheme();
@@ -47,15 +73,7 @@ export function Sidebar() {
<span className="sidebar-brand-sub">wiki.suchtech.ru</span> <span className="sidebar-brand-sub">wiki.suchtech.ru</span>
</Link> </Link>
{nav.space ? ( <SpacePicker />
<div className="space-pick">
<span className="space-pick-icon">{nav.space.icon || nav.space.name[0]}</span>
<span className="space-pick-text">
<span className="space-pick-label">Пространство</span>
<span className="space-pick-name">{nav.space.name}</span>
</span>
</div>
) : null}
<nav className="tree" aria-label="Статьи"> <nav className="tree" aria-label="Статьи">
<NavLink to="/search" className="tree-link tree-link--top"> <NavLink to="/search" className="tree-link tree-link--top">
+17 -7
View File
@@ -1,6 +1,9 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
import { type ArticleListItem, type SectionDto, shortTitle } from '@kb/shared'; import { type ArticleListItem, type SectionDto, shortTitle } from '@kb/shared';
import { useTree } from './api'; import { useTree } from './api';
import { useStored } from './store';
export const SPACE_KEY = 'kb-space';
export interface SectionView extends SectionDto { export interface SectionView extends SectionDto {
/** Статьи раздела без закреплённой шпаргалки. */ /** Статьи раздела без закреплённой шпаргалки. */
@@ -10,12 +13,18 @@ export interface SectionView extends SectionDto {
/** Дерево в удобном для экранов виде: разделы со статьями, поиск статьи и раздела по slug. */ /** Дерево в удобном для экранов виде: разделы со статьями, поиск статьи и раздела по slug. */
export function useNav() { export function useNav() {
const { data, isLoading, error } = useTree(); const { data, isLoading, error } = useTree();
// Выбранное пространство запоминается на устройстве
const [spaceId] = useStored<string | null>(SPACE_KEY, null);
return useMemo(() => { return useMemo(() => {
const sections = data?.sections ?? []; const spaces = data?.spaces ?? [];
const space = spaces.find((s) => s.id === spaceId) ?? spaces[0] ?? null;
const sections = (data?.sections ?? []).filter((s) => !space || s.spaceId === space.id);
const articles = data?.articles ?? []; const articles = data?.articles ?? [];
const bySection = new Map<string, SectionDto>(sections.map((s) => [s.id, s])); // Поиск раздела по id идёт по всем пространствам: избранное и поиск показывают статьи отовсюду
const allById = new Map<string, SectionDto>((data?.sections ?? []).map((s) => [s.id, s]));
const bySlug = new Map<string, ArticleListItem>(articles.map((a) => [a.slug, a])); const bySlug = new Map<string, ArticleListItem>(articles.map((a) => [a.slug, a]));
const pinned = articles.find((a) => a.pinned) ?? null; const inSpace = new Set(sections.map((s) => s.id));
const pinned = articles.find((a) => a.pinned && inSpace.has(a.sectionId)) ?? articles.find((a) => a.pinned) ?? null;
const views: SectionView[] = sections const views: SectionView[] = sections
.map((s) => ({ ...s, articles: articles.filter((a) => a.sectionId === s.id && !a.pinned) })) .map((s) => ({ ...s, articles: articles.filter((a) => a.sectionId === s.id && !a.pinned) }))
@@ -25,18 +34,19 @@ export function useNav() {
return { return {
isLoading, isLoading,
error, error,
space: data?.spaces[0] ?? null, space,
spaces,
sections: views, sections: views,
/** Все разделы, включая пустые (для редактора и админки). */ /** Все разделы, включая пустые (для редактора и админки). */
allSections: sections, allSections: sections,
articles, articles,
pinned, pinned,
article: (slug: string) => bySlug.get(slug), article: (slug: string) => bySlug.get(slug),
sectionOf: (a: ArticleListItem | undefined) => (a ? bySection.get(a.sectionId) : undefined), sectionOf: (a: ArticleListItem | undefined) => (a ? allById.get(a.sectionId) : undefined),
/** Название для меню и списков: без названия раздела в начале. */ /** Название для меню и списков: без названия раздела в начале. */
short: (a: ArticleListItem) => shortTitle(a.title, bySection.get(a.sectionId)?.name), short: (a: ArticleListItem) => shortTitle(a.title, allById.get(a.sectionId)?.name),
}; };
}, [data, isLoading, error]); }, [data, isLoading, error, spaceId]);
} }
/** Адрес статьи: закреплённая шпаргалка живёт на своём экране. */ /** Адрес статьи: закреплённая шпаргалка живёт на своём экране. */
+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 { useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { plural } from '@kb/shared'; import { plural } from '@kb/shared';
import { Screen } from '../components/Shell'; import { Screen, SpacePicker } from '../components/Shell';
import { UserMenu } from '../components/UserMenu'; import { UserMenu } from '../components/UserMenu';
import { Caps, CodeTag, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui'; import { Caps, CodeTag, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
import { useArticle } from '../lib/api'; import { useArticle } from '../lib/api';
@@ -58,6 +58,12 @@ export function HomePage() {
<ThemeButton /> <ThemeButton />
</header> </header>
{nav.spaces.length > 1 ? (
<div className="home-space">
<SpacePicker />
</div>
) : null}
{/* Поле на главной только открывает экран поиска: печатать удобнее там, где сразу видны результаты */} {/* Поле на главной только открывает экран поиска: печатать удобнее там, где сразу видны результаты */}
<div className="home-search"> <div className="home-search">
<label className="search-field"> <label className="search-field">
+312
View File
@@ -0,0 +1,312 @@
/* Админка (макеты 07 и D7). */
.adm-grid {
display: flex;
flex-direction: column;
gap: var(--sp-10);
}
.adm-col {
display: flex;
flex-direction: column;
gap: var(--sp-10);
min-width: 0;
}
.adm-spaces {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: var(--sp-5);
}
.adm-space {
display: flex;
flex-direction: column;
border: var(--bw) solid var(--ln);
border-radius: var(--r-card);
background: var(--sf);
}
.adm-space--on {
border: 2px solid var(--ink);
}
.adm-space-pick {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--sp-4);
padding: var(--sp-8) var(--sp-8) var(--sp-2);
border: 0;
background: transparent;
color: var(--ink);
text-align: left;
cursor: pointer;
}
.space-icon {
width: 32px;
height: 32px;
border-radius: var(--r-tag);
background: var(--brand);
color: var(--brand-ink);
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
}
.adm-space-name {
font-weight: 700;
}
.adm-space-n {
font-size: var(--fs-14);
color: var(--ink2);
}
.adm-link {
flex: none;
min-height: var(--tap-sm);
padding: 0 var(--sp-6);
border: 0;
background: transparent;
color: var(--ink2);
font-size: var(--fs-14);
font-weight: 600;
text-decoration: underline;
cursor: pointer;
}
.adm-space .adm-link {
align-self: flex-start;
padding-left: var(--sp-8);
}
.adm-add {
min-height: 52px;
border-radius: var(--r-btn);
}
.adm-sec {
display: flex;
align-items: center;
gap: var(--sp-5);
min-height: var(--h-row);
padding: var(--sp-2) var(--sp-3) var(--sp-2) var(--sp-2);
background: var(--sf);
}
.adm-sec + .adm-sec {
border-top: var(--bw) solid var(--ln);
}
/* Строка, которую тащат: жёлтая, как в макете */
.adm-sec--drag {
background: var(--brand);
color: var(--brand-ink);
}
.adm-sec--drag .codetag {
border-color: var(--brand-ink);
}
.adm-sec--drag .adm-link,
.adm-sec--drag .adm-handle {
color: var(--brand-ink);
}
.adm-handle {
flex: none;
width: var(--tap-sm);
height: var(--tap);
border: 0;
background: transparent;
color: var(--ink2);
font-size: var(--fs-18);
letter-spacing: -3px;
cursor: grab;
/* Палец на ручке двигает строку, а не прокручивает страницу */
touch-action: none;
}
.adm-pos {
flex: none;
font-size: var(--fs-13);
opacity: 0.7;
}
.adm-sec-name {
flex: 1;
min-width: 0;
font-weight: 600;
line-height: var(--lh-snug);
}
.adm-sec-n {
flex: none;
font-size: var(--fs-13);
opacity: 0.7;
}
.adm-form {
display: flex;
flex-wrap: wrap;
gap: var(--sp-6);
padding: var(--sp-7);
border: 2px solid var(--ink);
border-radius: var(--r-card);
background: var(--sf);
}
.adm-form-grow {
flex: 1 1 200px;
}
.adm-form-short {
flex: 0 0 96px;
}
.adm-form-wide,
.adm-form-actions {
flex: 1 1 100%;
}
.adm-form-actions {
display: flex;
flex-wrap: wrap;
gap: var(--sp-4);
}
.adm-danger {
border-color: var(--redS);
color: var(--red);
}
.adm-colors {
display: flex;
flex-wrap: wrap;
gap: var(--sp-4);
}
.adm-color {
min-width: var(--tap);
height: var(--tap-sm);
padding: 0 var(--sp-5);
border: 2px solid transparent;
border-radius: var(--r-plaque);
color: var(--plq-ink-text);
font-weight: 700;
cursor: pointer;
}
.adm-color.plaque--ink {
color: var(--bg);
}
.adm-color--on {
outline: 3px solid var(--ink);
outline-offset: 2px;
}
.adm-user + .adm-user {
border-top: var(--bw) solid var(--ln);
}
.adm-user--blocked .adm-user-main,
.adm-user--blocked .avatar {
opacity: 0.55;
}
.adm-user-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--sp-4) var(--sp-6);
min-height: 68px;
padding: var(--sp-4) var(--sp-7);
}
.adm-user-main {
flex: 1 1 160px;
min-width: 0;
min-height: var(--tap-sm);
padding: 0;
border: 0;
background: transparent;
color: var(--ink);
text-align: left;
cursor: pointer;
}
.adm-user-name {
display: block;
font-weight: 700;
line-height: 1.25;
}
.adm-user-sub {
display: block;
font-size: var(--fs-13);
color: var(--ink2);
overflow-wrap: anywhere;
}
.adm-user-more {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--sp-4);
padding: 0 var(--sp-7) var(--sp-6);
}
.adm-user-more .adm-user-sub {
flex: 1 1 100%;
}
.adm-roles {
flex: none;
display: flex;
gap: var(--sp-1);
padding: 3px;
border: var(--bw) solid var(--ln);
border-radius: var(--r-md);
background: var(--sf2);
}
.adm-roles--wide {
align-self: flex-start;
}
.adm-role {
height: var(--h-chip);
padding: 0 var(--sp-5);
border: 0;
border-radius: 7px;
background: transparent;
color: var(--ink);
font-size: var(--fs-13);
font-weight: 500;
cursor: pointer;
}
.adm-role--on {
background: var(--ink);
color: var(--bg);
font-weight: 700;
}
.adm-invite {
display: flex;
flex-direction: column;
gap: var(--sp-5);
padding: var(--sp-9);
border: 2px solid var(--ink);
border-radius: var(--r-card);
background: var(--sf);
}
.adm-invite-title {
font-weight: 700;
font-size: var(--fs-18);
}
.adm-invite-text {
font-size: var(--fs-15);
color: var(--ink2);
}
.adm-invite-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--sp-4);
padding-top: var(--sp-5);
border-top: var(--bw) solid var(--ln);
}
.adm-invite-url {
flex: 1 1 100%;
min-width: 0;
height: var(--tap);
padding: 0 var(--sp-6);
border: var(--bw) solid var(--ln);
border-radius: var(--r-md);
background: var(--sf2);
color: var(--ink);
font-size: var(--fs-14);
text-overflow: ellipsis;
}
.adm-invite-meta {
flex: 1;
min-width: 0;
font-size: var(--fs-13);
color: var(--ink2);
}
@media (min-width: 1024px) {
.adm-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr);
gap: var(--sp-12);
align-items: start;
}
}
+64
View File
@@ -2471,3 +2471,67 @@ mark {
align-items: center; align-items: center;
gap: var(--sp-4); gap: var(--sp-4);
} }
/* ---------- Переключатель пространства ---------- */
.space-pick {
min-height: 52px;
display: flex;
align-items: center;
gap: var(--sp-5);
padding: 0 var(--sp-6);
border: var(--bw) solid var(--ln);
border-radius: var(--r-btn);
background: var(--sf2);
}
.space-pick-text {
flex: 1;
min-width: 0;
}
.space-pick-icon {
flex: none;
width: 28px;
height: 28px;
border-radius: var(--r-tag);
background: var(--brand);
color: var(--brand-ink);
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
font-size: var(--fs-15);
}
.space-pick-label {
display: block;
font-size: 0.6875rem;
color: var(--ink2);
text-transform: uppercase;
letter-spacing: var(--caps);
font-weight: 700;
line-height: 1.3;
}
.space-pick-name,
.space-pick-select {
display: block;
font-size: var(--fs-16);
font-weight: 700;
line-height: 1.3;
}
.space-pick-select {
width: 100%;
border: 0;
background: transparent;
color: var(--ink);
cursor: pointer;
}
.space-pick-select option {
background: var(--sf);
color: var(--ink);
}
@media (min-width: 1024px) {
.sidebar .space-pick {
margin: 0 var(--sp-6) var(--sp-6);
}
.home-space {
display: none;
}
}