21 lines
1.1 KiB
TypeScript
21 lines
1.1 KiB
TypeScript
import type { Book } from "../api/types";
|
|
import { groupByDir } from "./group";
|
|
|
|
export type SortKey = "added" | "title" | "progress";
|
|
export const SORT_LABEL: Record<SortKey, string> = { added: "最近入库", title: "标题", progress: "阅读进度" };
|
|
export type GroupMode = "flat" | "dir";
|
|
|
|
export function sortBooks(books: Book[], key: SortKey): Book[] {
|
|
const a = [...books];
|
|
if (key === "title") return a.sort((x, y) => x.title.localeCompare(y.title, "zh"));
|
|
if (key === "progress")
|
|
return a.sort((x, y) => y.percent - x.percent || (x.added_at < y.added_at ? 1 : x.added_at > y.added_at ? -1 : 0));
|
|
return a.sort((x, y) => (x.added_at < y.added_at ? 1 : x.added_at > y.added_at ? -1 : 0));
|
|
}
|
|
|
|
/** 页面分组视图:flat 一段无标题;dir 沿用「根目录置顶、目录名 locale 排序」。 */
|
|
export function sections(books: Book[], key: SortKey, mode: GroupMode): { label: string; books: Book[] }[] {
|
|
if (mode === "flat") return [{ label: "", books: sortBooks(books, key) }];
|
|
return groupByDir(sortBooks(books, key)).map((g) => ({ label: g.dir, books: g.books }));
|
|
}
|