Files
wiki-montazh/apps/web/src/lib/tree.ts
T
deonisiiandClaude Opus 5.5 2a8c2b5110 Этап 8: админка
- пространства: создание, значок, переименование, удаление пустых, переключатель пространства
- разделы: создание, код и цвет плашки, порядок перетаскиванием (мышь, палец, клавиатура)
- пользователи: список, роль, блокировка (сразу завершает сессии), удаление
- приглашения по одноразовой ссылке с ролью, копирование и отзыв

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:03:00 +03:00

54 lines
2.8 KiB
TypeScript

import { useMemo } from 'react';
import { type ArticleListItem, type SectionDto, shortTitle } from '@kb/shared';
import { useTree } from './api';
import { useStored } from './store';
export const SPACE_KEY = 'kb-space';
export interface SectionView extends SectionDto {
/** Статьи раздела без закреплённой шпаргалки. */
articles: ArticleListItem[];
}
/** Дерево в удобном для экранов виде: разделы со статьями, поиск статьи и раздела по slug. */
export function useNav() {
const { data, isLoading, error } = useTree();
// Выбранное пространство запоминается на устройстве
const [spaceId] = useStored<string | null>(SPACE_KEY, null);
return useMemo(() => {
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 ?? [];
// Поиск раздела по 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 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
.map((s) => ({ ...s, articles: articles.filter((a) => a.sectionId === s.id && !a.pinned) }))
// Раздел, в котором только закреплённая шпаргалка, в сетке не показываем: у неё своя карточка
.filter((s) => s.articles.length > 0);
return {
isLoading,
error,
space,
spaces,
sections: views,
/** Все разделы, включая пустые (для редактора и админки). */
allSections: sections,
articles,
pinned,
article: (slug: string) => bySlug.get(slug),
sectionOf: (a: ArticleListItem | undefined) => (a ? allById.get(a.sectionId) : undefined),
/** Название для меню и списков: без названия раздела в начале. */
short: (a: ArticleListItem) => shortTitle(a.title, allById.get(a.sectionId)?.name),
};
}, [data, isLoading, error, spaceId]);
}
/** Адрес статьи: закреплённая шпаргалка живёт на своём экране. */
export const articleHref = (a: { slug: string; pinned?: boolean }) => (a.pinned ? '/cheatsheet' : `/a/${a.slug}`);