Use splitTOCHref to support other ebook formats as discussed in foliate-js#45

This commit is contained in:
chrox
2024-12-20 22:44:35 +01:00
parent b581251b58
commit d7ccbbcaa2
4 changed files with 12 additions and 7 deletions
+1
View File
@@ -59,6 +59,7 @@ export interface BookDoc {
};
toc: Array<TOCItem>;
sections: Array<SectionItem>;
splitTOCHref(href: string): Array<string | number>;
getCover(): Promise<Blob | null>;
}
+2 -2
View File
@@ -114,13 +114,13 @@ export const useReaderStore = create<ReaderStore>((set, get) => ({
console.log('Loading book', key);
const { book: loadedBookDoc } = await new DocumentLoader(file).open();
const bookDoc = loadedBookDoc as BookDoc;
if (bookDoc.toc && bookDoc.sections) {
if (bookDoc.toc?.length > 0 && bookDoc.sections?.length > 0) {
updateTocID(bookDoc.toc);
const sections = bookDoc.sections.reduce((map: Record<string, SectionItem>, section) => {
map[section.id] = section;
return map;
}, {});
updateTocCFI(bookDoc.toc, sections);
updateTocCFI(bookDoc, bookDoc.toc, sections);
}
useBookDataStore.setState((state) => ({
booksData: {
+8 -4
View File
@@ -1,4 +1,4 @@
import { SectionItem, TOCItem, CFI } from '@/libs/document';
import { SectionItem, TOCItem, CFI, BookDoc } from '@/libs/document';
export const findParentPath = (toc: TOCItem[], href: string): TOCItem[] => {
for (const item of toc) {
@@ -47,17 +47,21 @@ export const updateTocID = (items: TOCItem[], index = 0): number => {
return index;
};
export const updateTocCFI = (items: TOCItem[], sections: { [id: string]: SectionItem }): void => {
export const updateTocCFI = (
bookDoc: BookDoc,
items: TOCItem[],
sections: { [id: string]: SectionItem },
): void => {
items.forEach((item) => {
if (item.href) {
const id = item.href.split('#')[0]!;
const id = bookDoc.splitTOCHref(item.href)[0]!;
const section = sections[id];
if (section) {
item.cfi = section.cfi;
}
}
if (item.subitems) {
updateTocCFI(item.subitems, sections);
updateTocCFI(bookDoc, item.subitems, sections);
}
});
};