import type { LibrarySectionItem } from "@/lib/api"; /** 章 → 其下小节(保持平铺顺序;顺序沿用后端 sort_order) */ export function groupSections(sections: LibrarySectionItem[]) { const groups: { chapter: LibrarySectionItem; subs: LibrarySectionItem[] }[] = []; for (const s of sections) { if (s.parent_id == null) { groups.push({ chapter: s, subs: [] }); } else { groups[groups.length - 1]?.subs.push(s); } } return groups; } export interface ChapterNav { /** 当前章下标(0 起) */ index: number; /** 章总数 */ total: number; prev: LibrarySectionItem | null; next: LibrarySectionItem | null; } /** 当前章在章节序列中的位置与相邻章(找不到回落第一章) */ export function chapterNav( groups: { chapter: LibrarySectionItem }[], currentId: number | null ): ChapterNav { const total = groups.length; let index = groups.findIndex((g) => g.chapter.id === currentId); if (index < 0) index = 0; return { index, total, prev: index > 0 ? groups[index - 1].chapter : null, next: index < total - 1 ? groups[index + 1].chapter : null, }; }