import { Empty, Layout, Menu, Notice, Space, Toaster, type MenuItem, } from '@stash/ui' import { useEffect, useMemo, useRef, useState } from 'react' import { BackToTop } from './components/common/BackToTop' import { ArticleDetailView } from './components/content/ArticleDetailView' import { AppGrid } from './components/content/AppGrid' import { CesCardGrid } from './components/content/CesCardGrid' import { ItemDetailView } from './components/content/ItemDetailView' import { ItemEditor } from './components/content/ItemEditor' import { PosterGrid } from './components/content/PosterGrid' import { SectionCard } from './components/content/SectionCard' import { SiteHeader } from './components/header/SiteHeader' import { SearchBar } from './components/search/SearchBar' import { LoginDialog } from './components/auth/LoginDialog' import { ProfileCard } from './components/sidebar/ProfileCard' import { ServicePanel } from './components/sidebar/ServicePanel' import { useProjects } from './useProjects' import { fetchSession, logout, type SessionState } from './auth' import { fetchSettings, type SettingsDocument, type SiteSettings, } from './settings' import { appDetailModel, posterDetailModel, posterToRelatedItem, toRelatedItem, type ItemDetailModel, } from './data/detail' import type { AppItem, ArticleItem, PosterItem, RelatedItem } from './data/types' import { fetchManage, type CardItem, type GroupNode, type ManageData } from './manage' import './App.css' /** * 新前台:分组树 + 卡片组合。 * * 路由: * / 首页(卡片按勾选分组渲染) * /g/<分组 key> 分组页(自身条目 + 子分组) * /g/<分组 key>/i/<条目> 条目详情 * 旧 /c/... 地址按第一个路径段当成分组 key,兼容老书签。 */ type Route = | { kind: 'home' } | { kind: 'group'; key: string } | { kind: 'item'; key: string; itemId: string } function parseRoute(pathname: string): Route { const segments = pathname.split('/').filter(Boolean) if ( (segments[0] === 'g' || segments[0] === 'c') && segments[1] !== undefined ) { if (segments[2] === 'i' && segments[3] !== undefined) { return { kind: 'item', key: decodeURIComponent(segments[1]), itemId: decodeURIComponent(segments[3]) } } return { kind: 'group', key: decodeURIComponent(segments[1]) } } return { kind: 'home' } } function useRoute() { const [route, setRoute] = useState(() => parseRoute(window.location.pathname)) useEffect(() => { const sync = () => setRoute(parseRoute(window.location.pathname)) window.addEventListener('popstate', sync) return () => window.removeEventListener('popstate', sync) }, []) const navigate = (path: string) => { if (window.location.pathname === path) return window.history.pushState({}, '', path) setRoute(parseRoute(path)) document.getElementById('page-scroll')?.scrollTo({ top: 0 }) window.scrollTo({ top: 0 }) } return { route, navigate } } function findGroup(groups: GroupNode[], key: string): GroupNode | undefined { for (const group of groups) { if (group.key === key) return group const found = findGroup(group.children, key) if (found !== undefined) return found } return undefined } function findPath(groups: GroupNode[], key: string, trail: GroupNode[] = []): GroupNode[] | undefined { for (const group of groups) { const next = [...trail, group] if (group.key === key) return next const found = findPath(group.children, key, next) if (found !== undefined) return found } return undefined } function findEntryInGroup( group: GroupNode, entryId: string, ): { group: GroupNode; entry: Record } | undefined { const direct = group.entries.find((candidate) => candidate.id === entryId) if (direct !== undefined) { return { group, entry: direct as unknown as Record } } for (const child of group.children) { const found = findEntryInGroup(child, entryId) if (found !== undefined) return found } return undefined } function findEntry( groups: GroupNode[], groupKey: string, entryId: string, ): { group: GroupNode; entry: Record } | undefined { const group = findGroup(groups, groupKey) if (group === undefined) return undefined return findEntryInGroup(group, entryId) } function groupEntryCount(group: GroupNode): number { return group.entries.length + group.children.reduce((total, child) => total + groupEntryCount(child), 0) } /** 分组子树里的全部条目(格式沿根分组继承,所以可以放在同一个网格里) */ function collectEntries(group: GroupNode): Record[] { return [ ...(group.entries as unknown as Record[]), ...group.children.flatMap((child) => collectEntries(child)), ] } function defaultLimit(group: GroupNode): number { return group.previewLimit ?? 6 } function entryFormat(entry: Record): 'apps' | 'posters' | 'articles' { const value = entry.format return value === 'posters' || value === 'articles' ? value : 'apps' } function matches(entry: Record, keyword: string): boolean { if (keyword === '') return true const text = [entry.name, entry.title, entry.description, entry.desc] .filter((value) => typeof value === 'string') .join(' ') .toLowerCase() return text.includes(keyword) } const TOP_OFFSET = 104 export default function AppNext() { const { status, projects, error, live, refreshing, refresh } = useProjects() const { route, navigate } = useRoute() const [manage, setManage] = useState({ groups: [], cards: [] }) const [loading, setLoading] = useState(true) const [keyword, setKeyword] = useState('') const [session, setSession] = useState(null) const [settings, setSettings] = useState(null) const [loginOpen, setLoginOpen] = useState(false) const [editingKey, setEditingKey] = useState(null) const [scrolled, setScrolled] = useState(false) const searchRef = useRef(null) const load = () => { void fetchManage().then((data) => { setManage(data) setLoading(false) }) } useEffect(() => { load() void fetchSession().then(setSession) void fetchSettings().then(setSettings) const source = new EventSource('/api/catalog/events') source.onmessage = () => load() return () => source.close() }, []) useEffect(() => { const content = document.getElementById('content-scroll') const main = content?.parentElement const body = main?.parentElement if ( !(content instanceof HTMLElement) || !(main instanceof HTMLElement) || !(body instanceof HTMLElement) ) { return } // 左右两栏放进同一个滚动容器:滚动区域从搜索框下方开始,两栏位移完全一致 const sider = body.querySelector('aside') body.id = 'page-scroll' body.style.overflowY = 'auto' body.style.overflowX = 'hidden' body.style.marginTop = `${TOP_OFFSET}px` body.style.height = `calc(100% - ${TOP_OFFSET}px)` content.style.overflow = 'visible' content.style.marginTop = '0' main.style.height = 'auto' if (sider instanceof HTMLElement) { sider.style.overflow = 'visible' sider.style.height = 'auto' sider.style.alignSelf = 'flex-start' } const onScroll = () => setScrolled(body.scrollTop > 4) const updateSticky = () => { const viewport = body.clientHeight const maxLeft = Math.max(0, sider instanceof HTMLElement ? sider.offsetHeight - viewport : 0) const offset = Math.max(0, body.scrollTop - maxLeft) if (sider instanceof HTMLElement) { sider.style.transform = offset > 0 ? `translateY(${offset}px)` : '' } } body.addEventListener('scroll', onScroll, { passive: true }) body.addEventListener('scroll', updateSticky, { passive: true }) window.addEventListener('resize', updateSticky) const observer = new ResizeObserver(updateSticky) observer.observe(content) if (sider instanceof HTMLElement) observer.observe(sider) onScroll() updateSticky() return () => { body.removeEventListener('scroll', onScroll) body.removeEventListener('scroll', updateSticky) window.removeEventListener('resize', updateSticky) observer.disconnect() body.id = '' body.style.overflowY = '' body.style.overflowX = '' body.style.marginTop = '' body.style.height = '' content.style.overflow = '' content.style.marginTop = '' main.style.height = '' if (sider instanceof HTMLElement) { sider.style.overflow = '' sider.style.height = '' sider.style.alignSelf = '' sider.style.transform = '' } } }, []) const site: SiteSettings = settings?.settings ?? { header: { enabled: true, speed: 24, items: [] }, sidebar: { show_profile: true, show_service: true, hidden: [], order: [], hidden_groups: [], shown_groups: [], group_order: {}, tree_hidden: [], tree_order: {}, }, sections: { hidden: [], order: [], titles: {}, limits: {} }, profile: { name: '本地管理员', role: '管理员', description: '', location: '', avatar: '', }, } const keywordLower = keyword.trim().toLowerCase() const sidebarItems: MenuItem[] = useMemo(() => { const hidden = new Set(site.sidebar.tree_hidden) const sortNodes = (nodes: GroupNode[], parentKey: string): GroupNode[] => { const ranks = new Map( (site.sidebar.tree_order[parentKey] ?? []).map((key, index) => [key, index] as const), ) return [...nodes].sort((a, b) => { const left = ranks.get(a.key) ?? Number.MAX_SAFE_INTEGER const right = ranks.get(b.key) ?? Number.MAX_SAFE_INTEGER if (left === right) return a.sort - b.sort return left - right }) } const build = (nodes: GroupNode[], parentKey: string): MenuItem[] => sortNodes(nodes, parentKey).flatMap((node) => { if (node.enabled === false) return [] if (hidden.has(node.key)) return build(node.children, node.key) const children = build(node.children, node.key) return [ { key: `g:${node.key}`, label: node.title, children: children.length > 0 ? children : undefined, }, ] }) return [{ key: 'home', label: '首页' }, ...build(manage.groups, '')] }, [manage.groups, site.sidebar.tree_hidden, site.sidebar.tree_order]) const activeKey = route.kind === 'home' ? 'home' : route.kind === 'group' ? `g:${route.key}` : `g:${route.key}` function renderEntries( group: GroupNode, entries: Record[], options: { detail?: boolean; limit?: number } = {}, ) { const filtered = entries.filter((entry) => matches(entry, keywordLower)) const limit = options.limit ?? filtered.length const items = filtered.slice(0, limit) const open = (itemId: string) => navigate(`/g/${encodeURIComponent(group.key)}/i/${encodeURIComponent(itemId)}`) return ( <> {(['apps', 'posters', 'articles'] as const).map((format) => { const subset = items.filter((entry) => entryFormat(entry) === format) if (subset.length === 0) return null return (
{format === 'posters' ? ( ) : format === 'articles' ? ( ) : ( )}
) })} ) } function renderGroupBlock(group: GroupNode, limit: number, showTitle: boolean) { const all = collectEntries(group).filter((entry) => matches(entry, keywordLower)) if (all.length === 0) return null return (
{showTitle &&

{group.title}

} {renderEntries(group, all, { limit })}
) } function renderLocalService(card: CardItem) { const items: AppItem[] = projects.map((project) => ({ id: project.name, name: project.name, desc: project.route_path, icon: project.name.slice(0, 1).toUpperCase(), href: project.route_path, badge: '本地项目', comment: '本地静态站点,由 Stash 直接托管。', views: 0, likes: 0, })) return ( {items.length > 0 ? ( ) : ( )} ) } function renderCard(card: CardItem) { const resolved = card.groups .map((ref) => ({ ref, group: findGroup(manage.groups, ref.groupKey) })) .filter( (item): item is { ref: typeof item.ref; group: GroupNode } => item.group !== undefined && item.group.enabled !== false, ) const total = resolved.reduce((sum, item) => sum + groupEntryCount(item.group), 0) const first = resolved[0]?.group if (resolved.length === 0 || total === 0) return null return ( {resolved.map(({ group, ref }) => renderGroupBlock(group, ref.previewLimit ?? defaultLimit(group), resolved.length > 1), )} ) } function renderHome() { const cards = manage.cards return (
{loading && } {!loading && cards.length === 0 && } {cards.map((card) => card.key === 'local-service' ? renderLocalService(card) : renderCard(card), )} {keywordLower !== '' && cards.length > 0 && ( 在卡片与分组内按标题过滤。 )}
) } function renderGroupPage(key: string) { const group = findGroup(manage.groups, key) if (group === undefined) { return } const trail = findPath(manage.groups, key) ?? [group] return (

{group.title}

[{groupEntryCount(group)}]
{group.entries.length > 0 ? ( renderEntries(group, group.entries) ) : group.children.some((child) => groupEntryCount(child) > 0) ? null : ( )} {group.children.map((child) => (
{child.entries.length > 0 ? ( renderEntries(child, child.entries, { limit: 12 }) ) : ( )}
))}
) } function renderItemPage(key: string, itemId: string) { const found = findEntry(manage.groups, key, itemId) if (found === undefined) { return } const { group, entry } = found const trail = findPath(manage.groups, group.key) ?? [group] const crumbs = [ { label: '首页', href: '/' }, ...trail.map((node) => ({ label: node.title, href: `/g/${encodeURIComponent(node.key)}`, })), { label: String(entry.name ?? entry.title ?? entry.id) }, ] const format = entryFormat(entry) if (format === 'articles') { const article = entry as unknown as ArticleItem return ( setEditingKey(String(entry.id))} canEdit={session?.authenticated === true} /> ) } const model: ItemDetailModel = format === 'posters' ? posterDetailModel(entry as unknown as PosterItem) : appDetailModel(entry as unknown as AppItem) const related: RelatedItem[] = format === 'posters' ? group.entries .filter((item) => item.id !== entry.id && entryFormat(item as unknown as Record) === format) .slice(0, 4) .map((item) => posterToRelatedItem(item as unknown as PosterItem)) : group.entries .filter((item) => item.id !== entry.id && entryFormat(item as unknown as Record) === format) .slice(0, 4) .map((item) => toRelatedItem(item as unknown as AppItem)) return ( navigate(`/g/${encodeURIComponent(group.key)}/i/${encodeURIComponent(next)}`)} onEdit={() => setEditingKey(String(entry.id))} canEdit={session?.authenticated === true} /> ) } return ( <> setLoginOpen(false)} onSuccess={(next) => { setSession(next) setLoginOpen(false) }} /> setEditingKey(null)} onSaved={() => { setEditingKey(null) load() }} />