Skip to content

Commit

Permalink
Refactored createChapterNavigationButton
Browse files Browse the repository at this point in the history
  • Loading branch information
jonbitgood committed Dec 11, 2024
1 parent 4ce37e4 commit cd33241
Showing 1 changed file with 15 additions and 23 deletions.
38 changes: 15 additions & 23 deletions src/AudioPlayerMedia.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,34 +59,26 @@ function createChapterNavigationButton(ctx, dir) {
return elem('button', {
className: ctx.class[`${dir}ChapterButton`],
innerHTML: ctx.icons[`${dir}Chapter`],
onclick: () => {
const action = dir === 'prev' ? prevChapter : nextChapter;
action(ctx);
}
onclick: () => changeChapter(ctx, dir)
});
}

export async function prevChapter(ctx) {
if ((ctx.currentChapter.number - 1) > 1) {
handleChapterChange(ctx, ctx.currentBook, (ctx.currentChapter.number - 1))
} else {
const index = ctx.currentBooks.data.findIndex(book => book.book_id === ctx.currentBook.book_id);
if(ctx.currentBooks.data[index - 1]) {
handleBookChange(ctx, ctx.currentBooks.data[index - 1].book_id)
handleChapterChange(ctx, ctx.currentBooks.data[index - 1], 1)
}
async function changeChapter(ctx, dir) {
const chapterChange = (dir === 'prev') ? -1 : 1;
const targetChapter = ctx.currentChapter.number + chapterChange;

const inCurrentBook = dir === 'prev' ? (targetChapter > 0) : (targetChapter < ctx.currentBook.chapters.length + 1);
if (inCurrentBook) {
handleChapterChange(ctx, ctx.currentBook, targetChapter);
return
}
}

export async function nextChapter(ctx) {
if (ctx.currentChapter.number < ctx.currentBook.chapters.length - 1) {
handleChapterChange(ctx, ctx.currentBook, (ctx.currentChapter.number + 1))
} else {
const index = ctx.currentBooks.data.findIndex(book => book.book_id === ctx.currentBook.book_id);
if(ctx.currentBooks.data[index + 1]) {
handleBookChange(ctx, ctx.currentBooks.data[index + 1].book_id)
handleChapterChange(ctx, ctx.currentBooks.data[index + 1], 1)
}
const currentIndex = ctx.currentBooks.data.findIndex(book => book.book_id === ctx.currentBook.book_id);
const targetIndex = currentIndex + chapterChange;
const targetBook = ctx.currentBooks.data[targetIndex];
if (targetBook) {
handleBookChange(ctx, targetBook.book_id);
handleChapterChange(ctx, targetBook, 1);
}
}

Expand Down

0 comments on commit cd33241

Please sign in to comment.