Introduce a new eBook reader with support for EPUB, MOBI, AZW3, and FB2 formats (#2258)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+3
-6
@@ -102,8 +102,7 @@ public class BookController {
|
||||
@ApiResponse(responseCode = "200", description = "Book content returned successfully")
|
||||
@GetMapping("/{bookId}/content")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
|
||||
return bookService.getBookContent(bookId);
|
||||
}
|
||||
|
||||
@@ -115,8 +114,7 @@ public class BookController {
|
||||
@GetMapping("/{bookId}/download")
|
||||
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Resource> downloadBook(
|
||||
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||
public ResponseEntity<Resource> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@@ -124,8 +122,7 @@ public class BookController {
|
||||
@ApiResponse(responseCode = "200", description = "Viewer settings returned successfully")
|
||||
@GetMapping("/{bookId}/viewer-setting")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -49,6 +49,7 @@ public class BookLoreUserTransformer {
|
||||
case PER_BOOK_SETTING -> userSettings.setPerBookSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PerBookSetting.class));
|
||||
case PDF_READER_SETTING -> userSettings.setPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PdfReaderSetting.class));
|
||||
case EPUB_READER_SETTING -> userSettings.setEpubReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.EpubReaderSetting.class));
|
||||
case EBOOK_READER_SETTING -> userSettings.setEbookReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.EbookReaderSetting.class));
|
||||
case CBX_READER_SETTING -> userSettings.setCbxReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.CbxReaderSetting.class));
|
||||
case NEW_PDF_READER_SETTING -> userSettings.setNewPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.NewPdfReaderSetting.class));
|
||||
case SIDEBAR_LIBRARY_SORTING -> userSettings.setSidebarLibrarySorting(objectMapper.readValue(value, SidebarSortOption.class));
|
||||
|
||||
@@ -63,6 +63,7 @@ public class BookLoreUser {
|
||||
public PdfReaderSetting pdfReaderSetting;
|
||||
public NewPdfReaderSetting newPdfReaderSetting;
|
||||
public EpubReaderSetting epubReaderSetting;
|
||||
public EbookReaderSetting ebookReaderSetting;
|
||||
public CbxReaderSetting cbxReaderSetting;
|
||||
public SidebarSortOption sidebarLibrarySorting;
|
||||
public SidebarSortOption sidebarShelfSorting;
|
||||
@@ -107,6 +108,7 @@ public class BookLoreUser {
|
||||
private Float coverSize;
|
||||
@JsonAlias("seriesCollapse")
|
||||
private Boolean seriesCollapsed;
|
||||
private Boolean overlayBookType;
|
||||
}
|
||||
|
||||
@Data
|
||||
@@ -129,6 +131,7 @@ public class BookLoreUser {
|
||||
private String view;
|
||||
@JsonAlias("seriesCollapse")
|
||||
private Boolean seriesCollapsed;
|
||||
private Boolean overlayBookType;
|
||||
}
|
||||
|
||||
@Data
|
||||
@@ -145,6 +148,25 @@ public class BookLoreUser {
|
||||
private String spread;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class EbookReaderSetting {
|
||||
private String fontFamily;
|
||||
private Integer fontSize;
|
||||
private Float gap;
|
||||
private Boolean hyphenate;
|
||||
private Boolean isDark;
|
||||
private Boolean justify;
|
||||
private Float lineHeight;
|
||||
private Integer maxBlockSize;
|
||||
private Integer maxColumnCount;
|
||||
private Integer maxInlineSize;
|
||||
private String theme;
|
||||
private String flow;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
|
||||
+1
-1
@@ -8,6 +8,6 @@ import lombok.Data;
|
||||
public class BookViewerSettings {
|
||||
private PdfViewerPreferences pdfSettings;
|
||||
private NewPdfViewerPreferences newPdfSettings;
|
||||
private EpubViewerPreferences epubSettings;
|
||||
private EbookViewerPreferences ebookSettings;
|
||||
private CbxViewerPreferences cbxSettings;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class EbookViewerPreferences {
|
||||
private Long bookId;
|
||||
private Long userId;
|
||||
private String fontFamily;
|
||||
private Integer fontSize;
|
||||
private Float gap;
|
||||
private Boolean hyphenate;
|
||||
private Boolean isDark;
|
||||
private Boolean justify;
|
||||
private Float lineHeight;
|
||||
private Integer maxBlockSize;
|
||||
private Integer maxColumnCount;
|
||||
private Integer maxInlineSize;
|
||||
private String theme;
|
||||
private String flow;
|
||||
}
|
||||
|
||||
+1
@@ -9,6 +9,7 @@ import lombok.Data;
|
||||
public class EpubProgress {
|
||||
@NotNull
|
||||
String cfi;
|
||||
String href;
|
||||
@NotNull
|
||||
Float percentage;
|
||||
}
|
||||
|
||||
+3
-1
@@ -24,7 +24,9 @@ public class MetadataPersistenceSettings {
|
||||
private FormatSettings cbx;
|
||||
|
||||
public boolean isAnyFormatEnabled() {
|
||||
return (epub != null && epub.isEnabled()) || (pdf != null && pdf.isEnabled() || (cbx != null && cbx.isEnabled()));
|
||||
return (epub != null && epub.isEnabled())
|
||||
|| (pdf != null && pdf.isEnabled())
|
||||
|| (cbx != null && cbx.isEnabled());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ public enum UserSettingKey {
|
||||
PDF_READER_SETTING("pdfReaderSetting", true),
|
||||
NEW_PDF_READER_SETTING("newPdfReaderSetting", true),
|
||||
EPUB_READER_SETTING("epubReaderSetting", true),
|
||||
EBOOK_READER_SETTING("ebookReaderSetting", true),
|
||||
CBX_READER_SETTING("cbxReaderSetting", true),
|
||||
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
|
||||
SIDEBAR_SHELF_SORTING("sidebarShelfSorting", true),
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "ebook_viewer_preference", uniqueConstraints = {
|
||||
@UniqueConstraint(columnNames = {"user_id", "book_id"})
|
||||
})
|
||||
public class EbookViewerPreferenceEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "book_id", nullable = false)
|
||||
private Long bookId;
|
||||
|
||||
@Column(name = "font_family", nullable = false)
|
||||
private String fontFamily;
|
||||
|
||||
@Column(name = "font_size", nullable = false)
|
||||
private Integer fontSize;
|
||||
|
||||
@Column(name = "gap", nullable = false)
|
||||
private Float gap;
|
||||
|
||||
@Column(name = "hyphenate", nullable = false)
|
||||
private Boolean hyphenate;
|
||||
|
||||
@Column(name = "is_dark", nullable = false)
|
||||
private Boolean isDark;
|
||||
|
||||
@Column(name = "justify", nullable = false)
|
||||
private Boolean justify;
|
||||
|
||||
@Column(name = "line_height", nullable = false)
|
||||
private Float lineHeight;
|
||||
|
||||
@Column(name = "max_block_size", nullable = false)
|
||||
private Integer maxBlockSize;
|
||||
|
||||
@Column(name = "max_column_count", nullable = false)
|
||||
private Integer maxColumnCount;
|
||||
|
||||
@Column(name = "max_inline_size", nullable = false)
|
||||
private Integer maxInlineSize;
|
||||
|
||||
@Column(name = "theme", nullable = false)
|
||||
private String theme;
|
||||
|
||||
@Column(name = "flow", nullable = false)
|
||||
private String flow;
|
||||
}
|
||||
|
||||
+3
@@ -39,6 +39,9 @@ public class UserBookProgressEntity {
|
||||
@Column(name = "epub_progress", length = 1000)
|
||||
private String epubProgress;
|
||||
|
||||
@Column(name = "epub_progress_href", length = 1000)
|
||||
private String epubProgressHref;
|
||||
|
||||
@Column(name = "epub_progress_percent")
|
||||
private Float epubProgressPercent;
|
||||
|
||||
|
||||
+3
@@ -14,6 +14,9 @@ public enum BookFileExtension {
|
||||
CBZ("cbz", BookFileType.CBX),
|
||||
CBR("cbr", BookFileType.CBX),
|
||||
CB7("cb7", BookFileType.CBX),
|
||||
MOBI("mobi", BookFileType.MOBI),
|
||||
AZW3("azw3", BookFileType.AZW3),
|
||||
AZW("azw", BookFileType.AZW3),
|
||||
FB2("fb2", BookFileType.FB2);
|
||||
|
||||
private final String extension;
|
||||
|
||||
@@ -12,7 +12,9 @@ public enum BookFileType {
|
||||
PDF(Set.of("pdf")),
|
||||
EPUB(Set.of("epub")),
|
||||
CBX(Set.of("cbz", "cbr", "cb7")),
|
||||
FB2(Set.of("fb2"));
|
||||
FB2(Set.of("fb2")),
|
||||
MOBI(Set.of("mobi")),
|
||||
AZW3(Set.of("azw3", "azw"));
|
||||
|
||||
private final Set<String> extensions;
|
||||
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.EbookViewerPreferenceEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface EbookViewerPreferenceRepository extends JpaRepository<EbookViewerPreferenceEntity, Long> {
|
||||
|
||||
Optional<EbookViewerPreferenceEntity> findByBookIdAndUserId(Long bookId, Long userId);
|
||||
|
||||
}
|
||||
|
||||
+28
-102
@@ -4,30 +4,25 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.progress.*;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.CbxViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.entity.NewPdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.service.user.UserProgressService;
|
||||
import com.adityachandel.booklore.util.BookProgressUtil;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
import org.springframework.core.io.*;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -41,7 +36,6 @@ import java.net.MalformedURLException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -52,7 +46,6 @@ public class BookService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
private final FileService fileService;
|
||||
@@ -64,46 +57,9 @@ public class BookService {
|
||||
private final BookDownloadService bookDownloadService;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final BookUpdateService bookUpdateService;
|
||||
private final EbookViewerPreferenceRepository ebookViewerPreferencesRepository;
|
||||
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(KoboProgress.builder()
|
||||
.percentage(progress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> {
|
||||
book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
book.setKoreaderProgress(KoProgress.builder()
|
||||
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
|
||||
.build());
|
||||
}
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
private void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
book.setPersonalRating(progress.getPersonalRating());
|
||||
}
|
||||
}
|
||||
|
||||
public List<Book> getBookDTOs(boolean includeDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
@@ -125,7 +81,7 @@ public class BookService {
|
||||
);
|
||||
|
||||
books.forEach(book -> {
|
||||
enrichBookWithProgress(book, progressMap.get(book.getId()));
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(book.getId()));
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
});
|
||||
|
||||
@@ -144,7 +100,7 @@ public class BookService {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
if (!withDescription) book.getMetadata().setDescription(null);
|
||||
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
return book;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
@@ -158,46 +114,8 @@ public class BookService {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
book.setLastReadTime(userProgress.getLastReadTime());
|
||||
|
||||
if (userProgress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(KoboProgress.builder()
|
||||
.percentage(userProgress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
bookEntity.getBookFiles().iterator().forEachRemaining(bookFile -> {
|
||||
if (bookFile.getBookType() == BookFileType.PDF) {
|
||||
book.setPdfProgress(PdfProgress.builder()
|
||||
.page(userProgress.getPdfProgress())
|
||||
.percentage(userProgress.getPdfProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
if (bookFile.getBookType() == BookFileType.EPUB) {
|
||||
book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(userProgress.getEpubProgress())
|
||||
.percentage(userProgress.getEpubProgressPercent())
|
||||
.build());
|
||||
if (userProgress.getKoreaderProgressPercent() != null) {
|
||||
if (book.getKoreaderProgress() == null) {
|
||||
book.setKoreaderProgress(KoProgress.builder().build());
|
||||
}
|
||||
book.getKoreaderProgress().setPercentage(userProgress.getKoreaderProgressPercent() * 100);
|
||||
}
|
||||
}
|
||||
|
||||
if (bookFile.getBookType() == BookFileType.CBX) {
|
||||
book.setCbxProgress(CbxProgress.builder()
|
||||
.page(userProgress.getCbxProgress())
|
||||
.percentage(userProgress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
});
|
||||
|
||||
BookProgressUtil.enrichBookWithProgress(book, userProgress);
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
book.setReadStatus(userProgress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(userProgress.getReadStatus()));
|
||||
book.setDateFinished(userProgress.getDateFinished());
|
||||
book.setPersonalRating(userProgress.getPersonalRating());
|
||||
|
||||
if (!withDescription) {
|
||||
book.getMetadata().setDescription(null);
|
||||
@@ -206,26 +124,35 @@ public class BookService {
|
||||
return book;
|
||||
}
|
||||
|
||||
|
||||
public BookViewerSettings getBookViewerSetting(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
BookViewerSettings.BookViewerSettingsBuilder settingsBuilder = BookViewerSettings.builder();
|
||||
BookFileEntity bookFileEntity = bookEntity.getPrimaryBookFile();
|
||||
|
||||
if (bookFileEntity.getBookType() == BookFileType.EPUB) {
|
||||
epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(epubPref -> settingsBuilder.epubSettings(EpubViewerPreferences.builder()
|
||||
BookFileType bookType = bookEntity.getPrimaryBookFile().getBookType();
|
||||
if (bookType == BookFileType.EPUB || bookType == BookFileType.FB2
|
||||
|| bookType == BookFileType.MOBI
|
||||
|| bookType == BookFileType.AZW3) {
|
||||
ebookViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(epubPref -> settingsBuilder.ebookSettings(EbookViewerPreferences.builder()
|
||||
.bookId(bookId)
|
||||
.font(epubPref.getFont())
|
||||
.userId(user.getId())
|
||||
.fontFamily(epubPref.getFontFamily())
|
||||
.fontSize(epubPref.getFontSize())
|
||||
.gap(epubPref.getGap())
|
||||
.hyphenate(epubPref.getHyphenate())
|
||||
.isDark(epubPref.getIsDark())
|
||||
.justify(epubPref.getJustify())
|
||||
.lineHeight(epubPref.getLineHeight())
|
||||
.maxBlockSize(epubPref.getMaxBlockSize())
|
||||
.maxColumnCount(epubPref.getMaxColumnCount())
|
||||
.maxInlineSize(epubPref.getMaxInlineSize())
|
||||
.theme(epubPref.getTheme())
|
||||
.flow(epubPref.getFlow())
|
||||
.spread(epubPref.getSpread())
|
||||
.letterSpacing(epubPref.getLetterSpacing())
|
||||
.lineHeight(epubPref.getLineHeight())
|
||||
.build()));
|
||||
} else if (bookFileEntity.getBookType() == BookFileType.PDF) {
|
||||
} else if (bookType == BookFileType.PDF) {
|
||||
pdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(pdfPref -> settingsBuilder.pdfSettings(PdfViewerPreferences.builder()
|
||||
.bookId(bookId)
|
||||
@@ -238,7 +165,7 @@ public class BookService {
|
||||
.pageViewMode(pdfPref.getPageViewMode())
|
||||
.pageSpread(pdfPref.getPageSpread())
|
||||
.build()));
|
||||
} else if (bookFileEntity.getBookType() == BookFileType.CBX) {
|
||||
} else if (bookType == BookFileType.CBX) {
|
||||
cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(cbxPref -> settingsBuilder.cbxSettings(CbxViewerPreferences.builder()
|
||||
.bookId(bookId)
|
||||
@@ -318,7 +245,6 @@ public class BookService {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<BookDeletionResponse> deleteBooks(Set<Long> ids) {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
|
||||
|
||||
+329
-298
@@ -1,64 +1,46 @@
|
||||
package com.adityachandel.booklore.service.book;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettings;
|
||||
import com.adityachandel.booklore.model.dto.CbxViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.EpubViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.NewPdfViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.PdfViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.progress.CbxProgress;
|
||||
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
|
||||
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.CbxViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.NewPdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.model.enums.ResetProgressType;
|
||||
import com.adityachandel.booklore.model.enums.UserPermission;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.CbxViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.EpubViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.NewPdfViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
|
||||
import com.adityachandel.booklore.service.user.UserProgressService;
|
||||
import com.adityachandel.booklore.util.BookProgressUtil;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class BookUpdateService {
|
||||
|
||||
private static final float READING_THRESHOLD = 0.5f;
|
||||
private static final float COMPLETED_THRESHOLD = 99.5f;
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
private final ShelfRepository shelfRepository;
|
||||
@@ -69,132 +51,41 @@ public class BookUpdateService {
|
||||
private final BookQueryService bookQueryService;
|
||||
private final UserProgressService userProgressService;
|
||||
private final KoboReadingStateService koboReadingStateService;
|
||||
private final EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
|
||||
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookFileEntity bookFileEntity = bookEntity.getPrimaryBookFile();
|
||||
BookEntity book = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if (bookFileEntity.getBookType() == BookFileType.PDF) {
|
||||
if (bookViewerSettings.getPdfSettings() != null) {
|
||||
PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return pdfViewerPreferencesRepository.save(newPrefs);
|
||||
});
|
||||
PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings();
|
||||
pdfPrefs.setZoom(pdfSettings.getZoom());
|
||||
pdfPrefs.setSpread(pdfSettings.getSpread());
|
||||
pdfViewerPreferencesRepository.save(pdfPrefs);
|
||||
}
|
||||
if (bookViewerSettings.getNewPdfSettings() != null) {
|
||||
NewPdfViewerPreferencesEntity pdfPrefs = newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
NewPdfViewerPreferencesEntity entity = NewPdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return newPdfViewerPreferencesRepository.save(entity);
|
||||
});
|
||||
NewPdfViewerPreferences pdfSettings = bookViewerSettings.getNewPdfSettings();
|
||||
pdfPrefs.setPageSpread(pdfSettings.getPageSpread());
|
||||
pdfPrefs.setPageViewMode(pdfSettings.getPageViewMode());
|
||||
newPdfViewerPreferencesRepository.save(pdfPrefs);
|
||||
}
|
||||
} else if (bookFileEntity.getBookType() == BookFileType.EPUB) {
|
||||
EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
EpubViewerPreferencesEntity newPrefs = EpubViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return epubViewerPreferencesRepository.save(newPrefs);
|
||||
});
|
||||
|
||||
EpubViewerPreferences epubSettings = bookViewerSettings.getEpubSettings();
|
||||
epubPrefs.setFont(epubSettings.getFont());
|
||||
epubPrefs.setFontSize(epubSettings.getFontSize());
|
||||
epubPrefs.setTheme(epubSettings.getTheme());
|
||||
epubPrefs.setFlow(epubSettings.getFlow());
|
||||
epubPrefs.setSpread(epubSettings.getSpread());
|
||||
epubPrefs.setLetterSpacing(epubSettings.getLetterSpacing());
|
||||
epubPrefs.setLineHeight(epubSettings.getLineHeight());
|
||||
epubViewerPreferencesRepository.save(epubPrefs);
|
||||
|
||||
} else if (bookFileEntity.getBookType() == BookFileType.CBX) {
|
||||
CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return cbxViewerPreferencesRepository.save(newPrefs);
|
||||
});
|
||||
|
||||
CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings();
|
||||
cbxPrefs.setPageSpread(cbxSettings.getPageSpread());
|
||||
cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode());
|
||||
cbxPrefs.setFitMode(cbxSettings.getFitMode());
|
||||
cbxPrefs.setScrollMode(cbxSettings.getScrollMode());
|
||||
cbxPrefs.setBackgroundColor(cbxSettings.getBackgroundColor());
|
||||
cbxViewerPreferencesRepository.save(cbxPrefs);
|
||||
|
||||
} else {
|
||||
if (book.getPrimaryBookFile().getBookType() == null) {
|
||||
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
switch (book.getPrimaryBookFile().getBookType()) {
|
||||
case PDF -> updatePdfViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
case EPUB, FB2, MOBI, AZW3 -> updateEbookViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
case CBX -> updateCbxViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateReadProgress(ReadProgressRequest request) {
|
||||
BookEntity book = bookRepository.findByIdWithBookFiles(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
UserBookProgressEntity progress = userBookProgressRepository
|
||||
.findByUserIdAndBookId(user.getId(), book.getId())
|
||||
.orElseGet(UserBookProgressEntity::new);
|
||||
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId())
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(user.getId());
|
||||
progress.setUser(userEntity);
|
||||
|
||||
progress.setBook(book);
|
||||
progress.setLastReadTime(Instant.now());
|
||||
|
||||
Float percentage = null;
|
||||
BookFileEntity bookFileEntity = book.getPrimaryBookFile();
|
||||
switch (bookFileEntity.getBookType()) {
|
||||
case EPUB -> {
|
||||
if (request.getEpubProgress() != null) {
|
||||
progress.setEpubProgress(request.getEpubProgress().getCfi());
|
||||
percentage = request.getEpubProgress().getPercentage();
|
||||
}
|
||||
}
|
||||
case PDF -> {
|
||||
if (request.getPdfProgress() != null) {
|
||||
progress.setPdfProgress(request.getPdfProgress().getPage());
|
||||
percentage = request.getPdfProgress().getPercentage();
|
||||
}
|
||||
}
|
||||
case CBX -> {
|
||||
if (request.getCbxProgress() != null) {
|
||||
progress.setCbxProgress(request.getCbxProgress().getPage());
|
||||
percentage = request.getCbxProgress().getPercentage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Float percentage = updateProgressByBookType(progress, book.getPrimaryBookFile().getBookType(), request);
|
||||
if (percentage != null) {
|
||||
progress.setReadStatus(getStatus(percentage));
|
||||
setProgressPercent(progress, bookFileEntity.getBookType(), percentage);
|
||||
progress.setReadStatus(calculateReadStatus(percentage));
|
||||
setProgressPercent(progress, book.getPrimaryBookFile().getBookType(), percentage);
|
||||
}
|
||||
|
||||
if (request.getDateFinished() != null) {
|
||||
progress.setDateFinished(request.getDateFinished());
|
||||
}
|
||||
@@ -205,161 +96,280 @@ public class BookUpdateService {
|
||||
@Transactional
|
||||
public List<BookStatusUpdateResponse> updateReadStatus(List<Long> bookIds, String status) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if(bookIds.size() > 1 && !UserPermission.CAN_BULK_RESET_BOOK_READ_STATUS.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_BULK_RESET_BOOK_READ_STATUS);
|
||||
}
|
||||
validateBulkOperationPermission(bookIds, user, UserPermission.CAN_BULK_RESET_BOOK_READ_STATUS);
|
||||
|
||||
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Instant dateFinished = readStatus == ReadStatus.READ ? now : null;
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdateReadStatus(user.getId(), new ArrayList<>(existingProgressBookIds), readStatus, now, dateFinished);
|
||||
}
|
||||
updateExistingProgress(user.getId(), existingProgressBookIds, readStatus, now, dateFinished);
|
||||
createNewProgress(user.getId(), bookIds, existingProgressBookIds, readStatus, now, dateFinished);
|
||||
|
||||
Set<Long> newProgressBookIds = bookIds.stream()
|
||||
.filter(id -> !existingProgressBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (!newProgressBookIds.isEmpty()) {
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(userEntity);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setReadStatus(readStatus);
|
||||
progress.setReadStatusModifiedTime(now);
|
||||
progress.setDateFinished(dateFinished);
|
||||
return progress;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(readStatus)
|
||||
.readStatusModifiedTime(now)
|
||||
.dateFinished(dateFinished)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildStatusUpdateResponses(bookIds, readStatus, now, dateFinished);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<BookStatusUpdateResponse> resetProgress(List<Long> bookIds, ResetProgressType type) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if(bookIds.size() > 1 && type == ResetProgressType.BOOKLORE && !UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS);
|
||||
}
|
||||
|
||||
if(bookIds.size() > 1 && type == ResetProgressType.KOREADER && !UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS);
|
||||
}
|
||||
validateResetPermission(bookIds, user, type);
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
if (type == ResetProgressType.BOOKLORE) {
|
||||
userBookProgressRepository.bulkResetBookloreProgress(user.getId(), new ArrayList<>(existingProgressBookIds), now);
|
||||
} else if (type == ResetProgressType.KOREADER) {
|
||||
userBookProgressRepository.bulkResetKoreaderProgress(user.getId(), new ArrayList<>(existingProgressBookIds));
|
||||
} else if (type == ResetProgressType.KOBO) {
|
||||
userBookProgressRepository.bulkResetKoboProgress(user.getId(), new ArrayList<>(existingProgressBookIds));
|
||||
existingProgressBookIds.forEach(koboReadingStateService::deleteReadingState);
|
||||
}
|
||||
performReset(user.getId(), existingProgressBookIds, type, now);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(null)
|
||||
.readStatusModifiedTime(existingProgressBookIds.contains(bookId) ? now : null)
|
||||
.dateFinished(null)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildResetResponses(bookIds, existingProgressBookIds, now);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<PersonalRatingUpdateResponse> updatePersonalRating(List<Long> bookIds, Integer rating) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), rating);
|
||||
}
|
||||
|
||||
Set<Long> newProgressBookIds = bookIds.stream()
|
||||
.filter(id -> !existingProgressBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
createProgressForRating(user.getId(), bookIds, existingProgressBookIds, rating);
|
||||
|
||||
if (!newProgressBookIds.isEmpty()) {
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(userEntity);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setPersonalRating(rating);
|
||||
return progress;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> PersonalRatingUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.personalRating(rating)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildRatingUpdateResponses(bookIds, rating);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<PersonalRatingUpdateResponse> resetPersonalRating(List<Long> bookIds) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), null);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> PersonalRatingUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.personalRating(null)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildRatingUpdateResponses(bookIds, null);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId()));
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(user.getId());
|
||||
|
||||
Set<Long> userShelfIds = userEntity.getShelves().stream().map(ShelfEntity::getId).collect(Collectors.toSet());
|
||||
validateShelfOwnership(userEntity, shelfIdsToAssign, shelfIdsToUnassign);
|
||||
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
|
||||
|
||||
updateBookShelves(bookEntities, shelvesToAssign, shelfIdsToUnassign);
|
||||
bookRepository.saveAll(bookEntities);
|
||||
|
||||
return buildBooksWithProgress(bookEntities, user.getId());
|
||||
}
|
||||
|
||||
private void updatePdfViewerSettings(long bookId, Long userId, BookViewerSettings settings) {
|
||||
if (settings.getPdfSettings() != null) {
|
||||
PdfViewerPreferencesEntity prefs = findOrCreatePdfPreferences(bookId, userId);
|
||||
PdfViewerPreferences pdfSettings = settings.getPdfSettings();
|
||||
prefs.setZoom(pdfSettings.getZoom());
|
||||
prefs.setSpread(pdfSettings.getSpread());
|
||||
pdfViewerPreferencesRepository.save(prefs);
|
||||
}
|
||||
|
||||
if (settings.getNewPdfSettings() != null) {
|
||||
NewPdfViewerPreferencesEntity prefs = findOrCreateNewPdfPreferences(bookId, userId);
|
||||
NewPdfViewerPreferences pdfSettings = settings.getNewPdfSettings();
|
||||
prefs.setPageSpread(pdfSettings.getPageSpread());
|
||||
prefs.setPageViewMode(pdfSettings.getPageViewMode());
|
||||
newPdfViewerPreferencesRepository.save(prefs);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateEbookViewerSettings(long bookId, Long userId, BookViewerSettings settings) {
|
||||
EbookViewerPreferenceEntity prefs = findOrCreateEbookPreferences(bookId, userId);
|
||||
EbookViewerPreferences epubSettings = settings.getEbookSettings();
|
||||
|
||||
prefs.setUserId(userId);
|
||||
prefs.setBookId(bookId);
|
||||
prefs.setFontFamily(epubSettings.getFontFamily());
|
||||
prefs.setFontSize(epubSettings.getFontSize());
|
||||
prefs.setGap(epubSettings.getGap());
|
||||
prefs.setHyphenate(epubSettings.getHyphenate());
|
||||
prefs.setIsDark(epubSettings.getIsDark());
|
||||
prefs.setJustify(epubSettings.getJustify());
|
||||
prefs.setLineHeight(epubSettings.getLineHeight());
|
||||
prefs.setMaxBlockSize(epubSettings.getMaxBlockSize());
|
||||
prefs.setMaxColumnCount(epubSettings.getMaxColumnCount());
|
||||
prefs.setMaxInlineSize(epubSettings.getMaxInlineSize());
|
||||
prefs.setTheme(epubSettings.getTheme());
|
||||
prefs.setFlow(epubSettings.getFlow());
|
||||
|
||||
ebookViewerPreferenceRepository.save(prefs);
|
||||
}
|
||||
|
||||
private void updateCbxViewerSettings(long bookId, Long userId, BookViewerSettings settings) {
|
||||
CbxViewerPreferencesEntity prefs = findOrCreateCbxPreferences(bookId, userId);
|
||||
CbxViewerPreferences cbxSettings = settings.getCbxSettings();
|
||||
|
||||
prefs.setPageSpread(cbxSettings.getPageSpread());
|
||||
prefs.setPageViewMode(cbxSettings.getPageViewMode());
|
||||
prefs.setFitMode(cbxSettings.getFitMode());
|
||||
prefs.setScrollMode(cbxSettings.getScrollMode());
|
||||
prefs.setBackgroundColor(cbxSettings.getBackgroundColor());
|
||||
|
||||
cbxViewerPreferencesRepository.save(prefs);
|
||||
}
|
||||
|
||||
private PdfViewerPreferencesEntity findOrCreatePdfPreferences(long bookId, Long userId) {
|
||||
return pdfViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> pdfViewerPreferencesRepository.save(
|
||||
PdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private NewPdfViewerPreferencesEntity findOrCreateNewPdfPreferences(long bookId, Long userId) {
|
||||
return newPdfViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> newPdfViewerPreferencesRepository.save(
|
||||
NewPdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private EbookViewerPreferenceEntity findOrCreateEbookPreferences(long bookId, Long userId) {
|
||||
return ebookViewerPreferenceRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> ebookViewerPreferenceRepository.save(
|
||||
EbookViewerPreferenceEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private CbxViewerPreferencesEntity findOrCreateCbxPreferences(long bookId, Long userId) {
|
||||
return cbxViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> cbxViewerPreferencesRepository.save(
|
||||
CbxViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private Float updateProgressByBookType(UserBookProgressEntity progress, BookFileType bookType, ReadProgressRequest request) {
|
||||
return switch (bookType) {
|
||||
case EPUB, FB2, MOBI, AZW3 -> updateEbookProgress(progress, request.getEpubProgress());
|
||||
case PDF -> updatePdfProgress(progress, request.getPdfProgress());
|
||||
case CBX -> updateCbxProgress(progress, request.getCbxProgress());
|
||||
};
|
||||
}
|
||||
|
||||
private Float updateEbookProgress(UserBookProgressEntity progress, EpubProgress epubProgress) {
|
||||
if (epubProgress == null) return null;
|
||||
progress.setEpubProgress(epubProgress.getCfi());
|
||||
progress.setEpubProgressHref(epubProgress.getHref());
|
||||
return epubProgress.getPercentage();
|
||||
}
|
||||
|
||||
private Float updatePdfProgress(UserBookProgressEntity progress, PdfProgress pdfProgress) {
|
||||
if (pdfProgress == null) return null;
|
||||
progress.setPdfProgress(pdfProgress.getPage());
|
||||
return pdfProgress.getPercentage();
|
||||
}
|
||||
|
||||
private Float updateCbxProgress(UserBookProgressEntity progress, CbxProgress cbxProgress) {
|
||||
if (cbxProgress == null) return null;
|
||||
progress.setCbxProgress(cbxProgress.getPage());
|
||||
return cbxProgress.getPercentage();
|
||||
}
|
||||
|
||||
private void updateExistingProgress(Long userId, Set<Long> bookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
if (!bookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdateReadStatus(userId, new ArrayList<>(bookIds), status, now, dateFinished);
|
||||
}
|
||||
}
|
||||
|
||||
private void createNewProgress(Long userId, List<Long> allBookIds, Set<Long> existingBookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
Set<Long> newProgressBookIds = allBookIds.stream()
|
||||
.filter(id -> !existingBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (newProgressBookIds.isEmpty()) return;
|
||||
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(userId);
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> createProgressEntity(userEntity, bookId, status, now, dateFinished))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
private UserBookProgressEntity createProgressEntity(BookLoreUserEntity user, Long bookId, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(user);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setReadStatus(status);
|
||||
progress.setReadStatusModifiedTime(now);
|
||||
progress.setDateFinished(dateFinished);
|
||||
return progress;
|
||||
}
|
||||
|
||||
private void performReset(Long userId, Set<Long> bookIds, ResetProgressType type, Instant now) {
|
||||
List<Long> bookIdList = new ArrayList<>(bookIds);
|
||||
|
||||
switch (type) {
|
||||
case BOOKLORE -> userBookProgressRepository.bulkResetBookloreProgress(userId, bookIdList, now);
|
||||
case KOREADER -> userBookProgressRepository.bulkResetKoreaderProgress(userId, bookIdList);
|
||||
case KOBO -> {
|
||||
userBookProgressRepository.bulkResetKoboProgress(userId, bookIdList);
|
||||
bookIds.forEach(koboReadingStateService::deleteReadingState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createProgressForRating(Long userId, List<Long> allBookIds, Set<Long> existingBookIds, Integer rating) {
|
||||
Set<Long> newProgressBookIds = allBookIds.stream()
|
||||
.filter(id -> !existingBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (newProgressBookIds.isEmpty()) return;
|
||||
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(userId);
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> createProgressEntityWithRating(userEntity, bookId, rating))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
private UserBookProgressEntity createProgressEntityWithRating(BookLoreUserEntity user, Long bookId, Integer rating) {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(user);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setPersonalRating(rating);
|
||||
return progress;
|
||||
}
|
||||
|
||||
private void validateShelfOwnership(BookLoreUserEntity user, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
Set<Long> userShelfIds = user.getShelves().stream()
|
||||
.map(ShelfEntity::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (!userShelfIds.containsAll(shelfIdsToAssign)) {
|
||||
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot assign shelves that do not belong to the user.");
|
||||
@@ -367,25 +377,53 @@ public class BookUpdateService {
|
||||
if (!userShelfIds.containsAll(shelfIdsToUnassign)) {
|
||||
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user.");
|
||||
}
|
||||
}
|
||||
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
|
||||
for (BookEntity bookEntity : bookEntities) {
|
||||
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
|
||||
bookEntity.getShelves().addAll(shelvesToAssign);
|
||||
private void updateBookShelves(List<BookEntity> books, List<ShelfEntity> shelvesToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
for (BookEntity book : books) {
|
||||
book.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
|
||||
book.getShelves().addAll(shelvesToAssign);
|
||||
}
|
||||
bookRepository.saveAll(bookEntities);
|
||||
}
|
||||
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(
|
||||
user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()));
|
||||
private List<Book> buildBooksWithProgress(List<BookEntity> bookEntities, Long userId) {
|
||||
Set<Long> bookIds = bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(userId, bookIds);
|
||||
|
||||
return bookEntities.stream().map(bookEntity -> {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
return book;
|
||||
}).collect(Collectors.toList());
|
||||
return bookEntities.stream()
|
||||
.map(bookEntity -> buildBook(bookEntity, userId, progressMap))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Book buildBook(BookEntity bookEntity, Long userId, Map<Long, UserBookProgressEntity> progressMap) {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), userId));
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
return book;
|
||||
}
|
||||
|
||||
private BookLoreUserEntity findUserOrThrow(Long userId) {
|
||||
return userRepository.findById(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
}
|
||||
|
||||
private void validateBulkOperationPermission(List<Long> bookIds, BookLoreUser user, UserPermission permission) {
|
||||
if (bookIds.size() > 1 && !permission.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(permission);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateResetPermission(List<Long> bookIds, BookLoreUser user, ResetProgressType type) {
|
||||
if (bookIds.size() <= 1) return;
|
||||
UserPermission permission = switch (type) {
|
||||
case BOOKLORE -> UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS;
|
||||
case KOREADER -> UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS;
|
||||
default -> null;
|
||||
};
|
||||
if (permission != null && !permission.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(permission);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> validateBooksAndGetExistingProgress(Long userId, List<Long> bookIds) {
|
||||
@@ -399,54 +437,47 @@ public class BookUpdateService {
|
||||
|
||||
private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) {
|
||||
switch (type) {
|
||||
case EPUB -> progress.setEpubProgressPercent(percentage);
|
||||
case EPUB, FB2, MOBI, AZW3 -> progress.setEpubProgressPercent(percentage);
|
||||
case PDF -> progress.setPdfProgressPercent(percentage);
|
||||
case CBX -> progress.setCbxProgressPercent(percentage);
|
||||
}
|
||||
}
|
||||
|
||||
private ReadStatus getStatus(Float percentage) {
|
||||
if (percentage >= 99.5f) return ReadStatus.READ;
|
||||
if (percentage > 0.5f) return ReadStatus.READING;
|
||||
private ReadStatus calculateReadStatus(Float percentage) {
|
||||
if (percentage >= COMPLETED_THRESHOLD) return ReadStatus.READ;
|
||||
if (percentage > READING_THRESHOLD) return ReadStatus.READING;
|
||||
return ReadStatus.UNREAD;
|
||||
}
|
||||
|
||||
private void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
book.setPersonalRating(progress.getPersonalRating());
|
||||
}
|
||||
private List<BookStatusUpdateResponse> buildStatusUpdateResponses(List<Long> bookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(status)
|
||||
.readStatusModifiedTime(now)
|
||||
.dateFinished(dateFinished)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(com.adityachandel.booklore.model.dto.progress.KoboProgress.builder()
|
||||
.percentage(progress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
private List<BookStatusUpdateResponse> buildResetResponses(List<Long> bookIds, Set<Long> existingBookIds, Instant now) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(null)
|
||||
.readStatusModifiedTime(existingBookIds.contains(bookId) ? now : null)
|
||||
.dateFinished(null)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> {
|
||||
book.setEpubProgress(com.adityachandel.booklore.model.dto.progress.EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
book.setKoreaderProgress(com.adityachandel.booklore.model.dto.progress.KoProgress.builder()
|
||||
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
|
||||
.build());
|
||||
}
|
||||
case PDF -> book.setPdfProgress(com.adityachandel.booklore.model.dto.progress.PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(com.adityachandel.booklore.model.dto.progress.CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
private List<PersonalRatingUpdateResponse> buildRatingUpdateResponses(List<Long> bookIds, Integer rating) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> PersonalRatingUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.personalRating(rating)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Set<Shelf> filterShelvesByUserId(Set<Shelf> shelves, Long userId) {
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.Azw3MetadataExtractor;
|
||||
import com.adityachandel.booklore.util.BookCoverUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class Azw3Processor extends AbstractFileProcessor implements BookFileProcessor {
|
||||
|
||||
private final Azw3MetadataExtractor azw3MetadataExtractor;
|
||||
|
||||
public Azw3Processor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
MetadataMatchService metadataMatchService,
|
||||
Azw3MetadataExtractor azw3MetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.azw3MetadataExtractor = azw3MetadataExtractor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookFileType fileType = determineFileType(libraryFile.getFileName());
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, fileType);
|
||||
setBookMetadata(bookEntity);
|
||||
if (generateCover(bookEntity)) {
|
||||
FileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
}
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
try {
|
||||
File azw3File = new File(FileUtils.getBookFullPath(bookEntity));
|
||||
byte[] coverData = azw3MetadataExtractor.extractCover(azw3File);
|
||||
|
||||
if (coverData == null || coverData.length == 0) {
|
||||
log.warn("No cover image found in AZW3 '{}'", bookEntity.getPrimaryBookFile());
|
||||
return false;
|
||||
}
|
||||
|
||||
return saveCoverImage(coverData, bookEntity.getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for AZW3 '{}': {}", bookEntity.getPrimaryBookFile(), e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookFileType> getSupportedTypes() {
|
||||
return List.of(BookFileType.AZW3);
|
||||
}
|
||||
|
||||
private BookFileType determineFileType(String fileName) {
|
||||
return BookFileType.AZW3;
|
||||
}
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
BookMetadata azw3Metadata = azw3MetadataExtractor.extractMetadata(bookFile);
|
||||
if (azw3Metadata == null) return;
|
||||
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
metadata.setTitle(truncate(azw3Metadata.getTitle(), 1000));
|
||||
metadata.setSubtitle(truncate(azw3Metadata.getSubtitle(), 1000));
|
||||
metadata.setDescription(truncate(azw3Metadata.getDescription(), 2000));
|
||||
metadata.setPublisher(truncate(azw3Metadata.getPublisher(), 1000));
|
||||
metadata.setPublishedDate(azw3Metadata.getPublishedDate());
|
||||
metadata.setSeriesName(truncate(azw3Metadata.getSeriesName(), 1000));
|
||||
metadata.setSeriesNumber(azw3Metadata.getSeriesNumber());
|
||||
metadata.setSeriesTotal(azw3Metadata.getSeriesTotal());
|
||||
metadata.setIsbn13(truncate(azw3Metadata.getIsbn13(), 64));
|
||||
metadata.setIsbn10(truncate(azw3Metadata.getIsbn10(), 64));
|
||||
metadata.setPageCount(azw3Metadata.getPageCount());
|
||||
|
||||
String lang = azw3Metadata.getLanguage();
|
||||
metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000));
|
||||
|
||||
metadata.setAsin(truncate(azw3Metadata.getAsin(), 20));
|
||||
metadata.setAmazonRating(azw3Metadata.getAmazonRating());
|
||||
metadata.setAmazonReviewCount(azw3Metadata.getAmazonReviewCount());
|
||||
metadata.setGoodreadsId(truncate(azw3Metadata.getGoodreadsId(), 100));
|
||||
metadata.setGoodreadsRating(azw3Metadata.getGoodreadsRating());
|
||||
metadata.setGoodreadsReviewCount(azw3Metadata.getGoodreadsReviewCount());
|
||||
metadata.setHardcoverId(truncate(azw3Metadata.getHardcoverId(), 100));
|
||||
metadata.setHardcoverRating(azw3Metadata.getHardcoverRating());
|
||||
metadata.setHardcoverReviewCount(azw3Metadata.getHardcoverReviewCount());
|
||||
metadata.setGoogleId(truncate(azw3Metadata.getGoogleId(), 100));
|
||||
metadata.setComicvineId(truncate(azw3Metadata.getComicvineId(), 100));
|
||||
metadata.setRanobedbId(truncate(azw3Metadata.getRanobedbId(), 100));
|
||||
metadata.setRanobedbRating(azw3Metadata.getRanobedbRating());
|
||||
|
||||
bookCreatorService.addAuthorsToBook(azw3Metadata.getAuthors(), bookEntity);
|
||||
|
||||
if (azw3Metadata.getCategories() != null) {
|
||||
Set<String> validSubjects = azw3Metadata.getCategories().stream()
|
||||
.filter(s -> s != null && !s.isBlank() && s.length() <= 100 && !s.contains("\n") && !s.contains("\r") && !s.contains(" "))
|
||||
.collect(Collectors.toSet());
|
||||
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception {
|
||||
BufferedImage originalImage = FileService.readImage(coverData);
|
||||
if (originalImage == null) {
|
||||
log.warn("Failed to decode cover image for AZW3");
|
||||
return false;
|
||||
}
|
||||
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
}
|
||||
}
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.MobiMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.BookCoverUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MobiProcessor extends AbstractFileProcessor implements BookFileProcessor {
|
||||
|
||||
private final MobiMetadataExtractor mobiMetadataExtractor;
|
||||
|
||||
public MobiProcessor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
MetadataMatchService metadataMatchService,
|
||||
MobiMetadataExtractor mobiMetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.mobiMetadataExtractor = mobiMetadataExtractor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookFileType fileType = determineFileType(libraryFile.getFileName());
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, fileType);
|
||||
setBookMetadata(bookEntity);
|
||||
if (generateCover(bookEntity)) {
|
||||
FileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
}
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
try {
|
||||
File mobiFile = new File(FileUtils.getBookFullPath(bookEntity));
|
||||
byte[] coverData = mobiMetadataExtractor.extractCover(mobiFile);
|
||||
|
||||
if (coverData == null || coverData.length == 0) {
|
||||
log.warn("No cover image found in MOBI '{}'", bookEntity.getPrimaryBookFile().getFileName());
|
||||
return false;
|
||||
}
|
||||
|
||||
return saveCoverImage(coverData, bookEntity.getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for MOBI '{}': {}", bookEntity.getPrimaryBookFile(), e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookFileType> getSupportedTypes() {
|
||||
return List.of(BookFileType.MOBI);
|
||||
}
|
||||
|
||||
private BookFileType determineFileType(String fileName) {
|
||||
String lowerCase = fileName.toLowerCase();
|
||||
return BookFileType.MOBI;
|
||||
}
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
BookMetadata mobiMetadata = mobiMetadataExtractor.extractMetadata(bookFile);
|
||||
if (mobiMetadata == null) return;
|
||||
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
metadata.setTitle(truncate(mobiMetadata.getTitle(), 1000));
|
||||
metadata.setSubtitle(truncate(mobiMetadata.getSubtitle(), 1000));
|
||||
metadata.setDescription(truncate(mobiMetadata.getDescription(), 2000));
|
||||
metadata.setPublisher(truncate(mobiMetadata.getPublisher(), 1000));
|
||||
metadata.setPublishedDate(mobiMetadata.getPublishedDate());
|
||||
metadata.setSeriesName(truncate(mobiMetadata.getSeriesName(), 1000));
|
||||
metadata.setSeriesNumber(mobiMetadata.getSeriesNumber());
|
||||
metadata.setSeriesTotal(mobiMetadata.getSeriesTotal());
|
||||
metadata.setIsbn13(truncate(mobiMetadata.getIsbn13(), 64));
|
||||
metadata.setIsbn10(truncate(mobiMetadata.getIsbn10(), 64));
|
||||
metadata.setPageCount(mobiMetadata.getPageCount());
|
||||
|
||||
String lang = mobiMetadata.getLanguage();
|
||||
metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000));
|
||||
|
||||
metadata.setAsin(truncate(mobiMetadata.getAsin(), 20));
|
||||
metadata.setAmazonRating(mobiMetadata.getAmazonRating());
|
||||
metadata.setAmazonReviewCount(mobiMetadata.getAmazonReviewCount());
|
||||
metadata.setGoodreadsId(truncate(mobiMetadata.getGoodreadsId(), 100));
|
||||
metadata.setGoodreadsRating(mobiMetadata.getGoodreadsRating());
|
||||
metadata.setGoodreadsReviewCount(mobiMetadata.getGoodreadsReviewCount());
|
||||
metadata.setHardcoverId(truncate(mobiMetadata.getHardcoverId(), 100));
|
||||
metadata.setHardcoverRating(mobiMetadata.getHardcoverRating());
|
||||
metadata.setHardcoverReviewCount(mobiMetadata.getHardcoverReviewCount());
|
||||
metadata.setGoogleId(truncate(mobiMetadata.getGoogleId(), 100));
|
||||
metadata.setComicvineId(truncate(mobiMetadata.getComicvineId(), 100));
|
||||
metadata.setRanobedbId(truncate(mobiMetadata.getRanobedbId(), 100));
|
||||
metadata.setRanobedbRating(mobiMetadata.getRanobedbRating());
|
||||
|
||||
bookCreatorService.addAuthorsToBook(mobiMetadata.getAuthors(), bookEntity);
|
||||
|
||||
if (mobiMetadata.getCategories() != null) {
|
||||
Set<String> validSubjects = mobiMetadata.getCategories().stream()
|
||||
.filter(s -> s != null && !s.isBlank() && s.length() <= 100 && !s.contains("\n") && !s.contains("\r") && !s.contains(" "))
|
||||
.collect(Collectors.toSet());
|
||||
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception {
|
||||
BufferedImage originalImage = FileService.readImage(coverData);
|
||||
if (originalImage == null) {
|
||||
log.warn("Failed to decode cover image for MOBI");
|
||||
return false;
|
||||
}
|
||||
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-8
@@ -562,23 +562,23 @@ public class MetadataRefreshService {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
protected <T> T resolveField(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, T> extractor) {
|
||||
protected <T > T resolveField(Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, T > extractor) {
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, extractor, Objects::nonNull);
|
||||
}
|
||||
|
||||
protected Integer resolveFieldAsInteger(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, Integer> fieldValueExtractor) {
|
||||
protected Integer resolveFieldAsInteger (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, Integer > fieldValueExtractor){
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor, Objects::nonNull);
|
||||
}
|
||||
|
||||
protected String resolveFieldAsString(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor) {
|
||||
protected String resolveFieldAsString (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor){
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, Objects::nonNull);
|
||||
}
|
||||
|
||||
protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
protected Set<String> resolveFieldAsList (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor){
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, (value) -> value != null && !value.isEmpty());
|
||||
}
|
||||
|
||||
private <T> T resolveFieldWithProviders(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, T> extractor, Predicate<T> isValidValue) {
|
||||
private <T > T resolveFieldWithProviders(Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, T > extractor, Predicate < T > isValidValue) {
|
||||
if (fieldProvider == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -599,7 +599,7 @@ public class MetadataRefreshService {
|
||||
return null;
|
||||
}
|
||||
|
||||
Set<String> getAllCategories(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> getAllCategories (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor){
|
||||
Set<String> uniqueCategories = new HashSet<>();
|
||||
if (fieldProvider == null) {
|
||||
return uniqueCategories;
|
||||
@@ -624,7 +624,7 @@ public class MetadataRefreshService {
|
||||
return uniqueCategories;
|
||||
}
|
||||
|
||||
protected Set<Long> getBookEntities(MetadataRefreshRequest request) {
|
||||
protected Set<Long> getBookEntities (MetadataRefreshRequest request){
|
||||
MetadataRefreshRequest.RefreshType refreshType = request.getRefreshType();
|
||||
if (refreshType != MetadataRefreshRequest.RefreshType.LIBRARY && refreshType != MetadataRefreshRequest.RefreshType.BOOKS) {
|
||||
throw ApiError.INVALID_REFRESH_TYPE.createException();
|
||||
@@ -638,4 +638,3 @@ public class MetadataRefreshService {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class Azw3MetadataExtractor extends MobiBaseMetadataExtractor {
|
||||
|
||||
private static final long KF8_BOUNDARY = 0xFFFFFFFF;
|
||||
|
||||
@Override
|
||||
protected String getFormatName() {
|
||||
return "AZW3";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void processFormatSpecificHeader(RandomAccessFile raf, PalmDBRecord record0, MobiHeader header, int headerLength) throws IOException {
|
||||
// For KF8 (AZW3), check for KF8 boundary and resource index
|
||||
if (header.isKF8 && headerLength >= 232) {
|
||||
raf.seek(record0.offset + 16 + 192);
|
||||
long kf8Boundary = readInt(raf) & 0xFFFFFFFFL;
|
||||
if (kf8Boundary == KF8_BOUNDARY) {
|
||||
log.debug("KF8 boundary found at expected location");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -16,6 +16,8 @@ public class MetadataExtractorFactory {
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
private final Fb2MetadataExtractor fb2MetadataExtractor;
|
||||
private final MobiMetadataExtractor mobiMetadataExtractor;
|
||||
private final Azw3MetadataExtractor azw3MetadataExtractor;
|
||||
|
||||
public BookMetadata extractMetadata(BookFileType bookFileType, File file) {
|
||||
return switch (bookFileType) {
|
||||
@@ -23,6 +25,8 @@ public class MetadataExtractorFactory {
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBX -> cbxMetadataExtractor.extractMetadata(file);
|
||||
case FB2 -> fb2MetadataExtractor.extractMetadata(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractMetadata(file);
|
||||
case AZW3 -> azw3MetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -32,6 +36,8 @@ public class MetadataExtractorFactory {
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractMetadata(file);
|
||||
case FB2 -> fb2MetadataExtractor.extractMetadata(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractMetadata(file);
|
||||
case AZW3, AZW -> azw3MetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +47,8 @@ public class MetadataExtractorFactory {
|
||||
case PDF -> pdfMetadataExtractor.extractCover(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractCover(file);
|
||||
case FB2 -> fb2MetadataExtractor.extractCover(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractCover(file);
|
||||
case AZW3, AZW -> azw3MetadataExtractor.extractCover(file);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+430
@@ -0,0 +1,430 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
public abstract class MobiBaseMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
// EXTH record types
|
||||
protected static final int EXTH_AUTHOR = 100;
|
||||
protected static final int EXTH_PUBLISHER = 101;
|
||||
protected static final int EXTH_DESCRIPTION = 103;
|
||||
protected static final int EXTH_ISBN = 104;
|
||||
protected static final int EXTH_SUBJECT = 105;
|
||||
protected static final int EXTH_PUBLISHED_DATE = 106;
|
||||
protected static final int EXTH_LANGUAGE = 524;
|
||||
protected static final int EXTH_COVER_OFFSET = 201;
|
||||
protected static final int EXTH_THUMB_OFFSET = 202;
|
||||
protected static final int EXTH_ASIN = 113;
|
||||
|
||||
protected abstract String getFormatName();
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
|
||||
PalmDB palmDB = readPalmDB(raf);
|
||||
if (palmDB == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
MobiHeader mobiHeader = readMobiHeader(raf, palmDB);
|
||||
if (mobiHeader == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Try to get cover from EXTH
|
||||
Integer coverIndex = mobiHeader.exthRecords.get(EXTH_COVER_OFFSET);
|
||||
if (coverIndex == null) {
|
||||
coverIndex = mobiHeader.exthRecords.get(EXTH_THUMB_OFFSET);
|
||||
}
|
||||
|
||||
if (coverIndex != null) {
|
||||
int imageRecordIndex = mobiHeader.firstImageIndex + coverIndex;
|
||||
if (imageRecordIndex < palmDB.records.size()) {
|
||||
return extractImageFromRecord(raf, palmDB.records.get(imageRecordIndex));
|
||||
}
|
||||
}
|
||||
|
||||
// Try first image
|
||||
if (mobiHeader.firstImageIndex > 0 && mobiHeader.firstImageIndex < palmDB.records.size()) {
|
||||
return extractImageFromRecord(raf, palmDB.records.get(mobiHeader.firstImageIndex));
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to extract cover from {}: {}", getFormatName(), file.getName(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File file) {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
|
||||
PalmDB palmDB = readPalmDB(raf);
|
||||
if (palmDB == null) {
|
||||
log.warn("Failed to read PalmDB header from: {}", file.getName());
|
||||
return null;
|
||||
}
|
||||
|
||||
MobiHeader mobiHeader = readMobiHeader(raf, palmDB);
|
||||
if (mobiHeader == null) {
|
||||
log.warn("Failed to read {} header from: {}", getFormatName(), file.getName());
|
||||
return null;
|
||||
}
|
||||
|
||||
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder();
|
||||
Set<String> authors = new HashSet<>();
|
||||
Set<String> categories = new HashSet<>();
|
||||
|
||||
// Extract title
|
||||
if (StringUtils.isNotBlank(mobiHeader.title)) {
|
||||
builder.title(mobiHeader.title);
|
||||
}
|
||||
|
||||
// Extract metadata from EXTH records
|
||||
for (var entry : mobiHeader.exthData.entrySet()) {
|
||||
int recordType = entry.getKey();
|
||||
String value = entry.getValue();
|
||||
|
||||
if (StringUtils.isBlank(value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (recordType) {
|
||||
case EXTH_AUTHOR -> authors.add(value.trim());
|
||||
case EXTH_PUBLISHER -> builder.publisher(value.trim());
|
||||
case EXTH_DESCRIPTION -> builder.description(value.trim());
|
||||
case EXTH_ISBN -> {
|
||||
String isbn = value.replaceAll("[^0-9Xx]", "");
|
||||
if (isbn.length() == 13) {
|
||||
builder.isbn13(isbn);
|
||||
} else if (isbn.length() == 10) {
|
||||
builder.isbn10(isbn);
|
||||
}
|
||||
}
|
||||
case EXTH_SUBJECT -> {
|
||||
for (String category : value.split("[;,]")) {
|
||||
String trimmed = category.trim();
|
||||
if (StringUtils.isNotBlank(trimmed)) {
|
||||
categories.add(trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
case EXTH_PUBLISHED_DATE -> {
|
||||
LocalDate date = parseDate(value.trim());
|
||||
if (date != null) {
|
||||
builder.publishedDate(date);
|
||||
}
|
||||
}
|
||||
case EXTH_LANGUAGE -> builder.language(value.trim());
|
||||
case EXTH_ASIN -> builder.asin(value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
builder.authors(authors);
|
||||
builder.categories(categories);
|
||||
|
||||
return builder.build();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to extract metadata from {}: {}", getFormatName(), file.getName(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected PalmDB readPalmDB(RandomAccessFile raf) throws IOException {
|
||||
if (raf.length() < 78) {
|
||||
log.debug("File too small for PalmDB");
|
||||
return null;
|
||||
}
|
||||
|
||||
PalmDB palmDB = new PalmDB();
|
||||
|
||||
// Read database name
|
||||
raf.seek(0);
|
||||
byte[] nameBytes = new byte[32];
|
||||
raf.readFully(nameBytes);
|
||||
int nameLen = 0;
|
||||
for (int i = 0; i < nameBytes.length; i++) {
|
||||
if (nameBytes[i] == 0) {
|
||||
nameLen = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
palmDB.name = new String(nameBytes, 0, nameLen, StandardCharsets.ISO_8859_1);
|
||||
|
||||
// Read number of records
|
||||
raf.seek(76);
|
||||
palmDB.numRecords = readShort(raf);
|
||||
|
||||
log.debug("PalmDB: name={}, records={}", palmDB.name, palmDB.numRecords);
|
||||
|
||||
if (palmDB.numRecords <= 0 || palmDB.numRecords > 10000) {
|
||||
log.debug("Invalid number of records: {}", palmDB.numRecords);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read record list
|
||||
raf.seek(78);
|
||||
for (int i = 0; i < palmDB.numRecords; i++) {
|
||||
PalmDBRecord record = new PalmDBRecord();
|
||||
record.offset = readInt(raf);
|
||||
record.attributes = raf.read();
|
||||
record.id = readThreeBytes(raf);
|
||||
palmDB.records.add(record);
|
||||
}
|
||||
|
||||
// Calculate record sizes
|
||||
for (int i = 0; i < palmDB.records.size(); i++) {
|
||||
PalmDBRecord record = palmDB.records.get(i);
|
||||
if (i < palmDB.records.size() - 1) {
|
||||
record.size = palmDB.records.get(i + 1).offset - record.offset;
|
||||
} else {
|
||||
record.size = (int) (raf.length() - record.offset);
|
||||
}
|
||||
}
|
||||
|
||||
return palmDB;
|
||||
}
|
||||
|
||||
protected MobiHeader readMobiHeader(RandomAccessFile raf, PalmDB palmDB) throws IOException {
|
||||
if (palmDB.records.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
PalmDBRecord record0 = palmDB.records.get(0);
|
||||
raf.seek(record0.offset);
|
||||
|
||||
MobiHeader header = new MobiHeader();
|
||||
|
||||
// Read PalmDOC header
|
||||
int compression = readShort(raf);
|
||||
raf.skipBytes(2);
|
||||
int textLength = readInt(raf);
|
||||
int recordCount = readShort(raf);
|
||||
int recordSize = readShort(raf);
|
||||
int encryptionType = readShort(raf);
|
||||
raf.skipBytes(2);
|
||||
|
||||
log.debug("PalmDOC: compression={}, textLength={}, recordCount={}, recordSize={}",
|
||||
compression, textLength, recordCount, recordSize);
|
||||
|
||||
// Check for MOBI header
|
||||
raf.seek(record0.offset + 16);
|
||||
byte[] identifier = new byte[4];
|
||||
raf.readFully(identifier);
|
||||
String identifierStr = new String(identifier, StandardCharsets.US_ASCII);
|
||||
|
||||
log.debug("Header identifier: {}", identifierStr);
|
||||
|
||||
if (!identifierStr.equals("MOBI")) {
|
||||
log.debug("No MOBI/KF8 header found");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read MOBI header
|
||||
raf.seek(record0.offset + 20);
|
||||
int headerLength = readInt(raf);
|
||||
int mobiType = readInt(raf);
|
||||
int textEncoding = readInt(raf);
|
||||
|
||||
log.debug("{}: headerLength={}, type={}, encoding={}", getFormatName(), headerLength, mobiType, textEncoding);
|
||||
|
||||
// Check if this is KF8 (AZW3) format
|
||||
header.isKF8 = (mobiType == 2);
|
||||
if (header.isKF8) {
|
||||
log.debug("Detected KF8 (AZW3) format");
|
||||
}
|
||||
|
||||
// Process format-specific logic
|
||||
processFormatSpecificHeader(raf, record0, header, headerLength);
|
||||
|
||||
// Determine charset
|
||||
Charset charset = textEncoding == 65001 ? StandardCharsets.UTF_8 : StandardCharsets.ISO_8859_1;
|
||||
header.charset = charset;
|
||||
|
||||
// Skip to full name offset/length
|
||||
raf.seek(record0.offset + 16 + 68);
|
||||
int fullNameOffset = readInt(raf);
|
||||
int fullNameLength = readInt(raf);
|
||||
|
||||
log.debug("Full name: offset={}, length={}", fullNameOffset, fullNameLength);
|
||||
|
||||
// Read title
|
||||
if (fullNameLength > 0 && fullNameLength < 10000) {
|
||||
raf.seek(record0.offset + fullNameOffset);
|
||||
byte[] titleBytes = new byte[fullNameLength];
|
||||
raf.readFully(titleBytes);
|
||||
header.title = new String(titleBytes, charset).trim();
|
||||
log.debug("Title: {}", header.title);
|
||||
}
|
||||
|
||||
// Read first image index
|
||||
raf.seek(record0.offset + 16 + 92);
|
||||
header.firstImageIndex = readInt(raf);
|
||||
|
||||
log.debug("First image index: {}", header.firstImageIndex);
|
||||
|
||||
// Check for EXTH header
|
||||
raf.seek(record0.offset + 16 + 112);
|
||||
int exthFlags = readInt(raf);
|
||||
|
||||
log.debug("EXTH flags: 0x{}", Integer.toHexString(exthFlags));
|
||||
|
||||
if ((exthFlags & 0x40) != 0) {
|
||||
long exthOffset = record0.offset + 16 + headerLength;
|
||||
raf.seek(exthOffset);
|
||||
|
||||
byte[] exthIdentifier = new byte[4];
|
||||
raf.readFully(exthIdentifier);
|
||||
String exthStr = new String(exthIdentifier, StandardCharsets.US_ASCII);
|
||||
|
||||
log.debug("EXTH identifier: {}", exthStr);
|
||||
|
||||
if (exthStr.equals("EXTH")) {
|
||||
readExthRecords(raf, header, charset);
|
||||
}
|
||||
}
|
||||
|
||||
return header;
|
||||
}
|
||||
|
||||
protected void processFormatSpecificHeader(RandomAccessFile raf, PalmDBRecord record0,
|
||||
MobiHeader header, int headerLength) throws IOException {
|
||||
// Override in subclasses for format-specific processing
|
||||
}
|
||||
|
||||
protected void readExthRecords(RandomAccessFile raf, MobiHeader header, Charset charset) throws IOException {
|
||||
long exthStart = raf.getFilePointer() - 4;
|
||||
|
||||
int headerLength = readInt(raf);
|
||||
int recordCount = readInt(raf);
|
||||
|
||||
log.debug("EXTH: headerLength={}, recordCount={}", headerLength, recordCount);
|
||||
|
||||
for (int i = 0; i < recordCount && i < 500; i++) {
|
||||
int recordType = readInt(raf);
|
||||
int recordLength = readInt(raf);
|
||||
|
||||
if (recordLength < 8 || recordLength > 100000) {
|
||||
log.warn("Invalid EXTH record length: {}", recordLength);
|
||||
break;
|
||||
}
|
||||
|
||||
int dataLength = recordLength - 8;
|
||||
byte[] data = new byte[dataLength];
|
||||
raf.readFully(data);
|
||||
|
||||
if (recordType == EXTH_COVER_OFFSET || recordType == EXTH_THUMB_OFFSET) {
|
||||
if (dataLength >= 4) {
|
||||
int value = ((data[0] & 0xFF) << 24) | ((data[1] & 0xFF) << 16) |
|
||||
((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
|
||||
header.exthRecords.put(recordType, value);
|
||||
log.debug("EXTH record {} (int): {}", recordType, value);
|
||||
}
|
||||
} else {
|
||||
String value = new String(data, charset).trim();
|
||||
value = value.replace("\0", "");
|
||||
if (!value.isEmpty()) {
|
||||
header.exthData.put(recordType, value);
|
||||
log.debug("EXTH record {} (string): {}", recordType,
|
||||
value.length() > 100 ? value.substring(0, 100) + "..." : value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected byte[] extractImageFromRecord(RandomAccessFile raf, PalmDBRecord record) throws IOException {
|
||||
if (record.size <= 0 || record.size > 10_000_000) {
|
||||
return null;
|
||||
}
|
||||
|
||||
raf.seek(record.offset);
|
||||
byte[] data = new byte[record.size];
|
||||
raf.readFully(data);
|
||||
|
||||
// Check for image magic bytes
|
||||
if (data.length > 4) {
|
||||
if ((data[0] == (byte) 0xFF && data[1] == (byte) 0xD8) || // JPEG
|
||||
(data[0] == (byte) 0x89 && data[1] == (byte) 0x50 &&
|
||||
data[2] == (byte) 0x4E && data[3] == (byte) 0x47) || // PNG
|
||||
(data[0] == (byte) 0x47 && data[1] == (byte) 0x49 &&
|
||||
data[2] == (byte) 0x46)) { // GIF
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected LocalDate parseDate(String dateString) {
|
||||
if (StringUtils.isBlank(dateString)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) {
|
||||
return LocalDate.parse(dateString);
|
||||
}
|
||||
|
||||
if (dateString.matches("\\d{4}")) {
|
||||
return LocalDate.of(Integer.parseInt(dateString), 1, 1);
|
||||
}
|
||||
|
||||
if (dateString.matches("\\d{4}/\\d{2}/\\d{2}")) {
|
||||
String[] parts = dateString.split("/");
|
||||
return LocalDate.of(Integer.parseInt(parts[0]),
|
||||
Integer.parseInt(parts[1]),
|
||||
Integer.parseInt(parts[2]));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to parse date: {}", dateString, e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected int readInt(RandomAccessFile raf) throws IOException {
|
||||
return (raf.read() << 24) | (raf.read() << 16) | (raf.read() << 8) | raf.read();
|
||||
}
|
||||
|
||||
protected int readShort(RandomAccessFile raf) throws IOException {
|
||||
return (raf.read() << 8) | raf.read();
|
||||
}
|
||||
|
||||
protected int readThreeBytes(RandomAccessFile raf) throws IOException {
|
||||
return (raf.read() << 16) | (raf.read() << 8) | raf.read();
|
||||
}
|
||||
|
||||
protected static class PalmDB {
|
||||
String name;
|
||||
int numRecords;
|
||||
List<PalmDBRecord> records = new ArrayList<>();
|
||||
}
|
||||
|
||||
protected static class PalmDBRecord {
|
||||
int offset;
|
||||
int attributes;
|
||||
int id;
|
||||
int size;
|
||||
}
|
||||
|
||||
protected static class MobiHeader {
|
||||
String title;
|
||||
int firstImageIndex = -1;
|
||||
boolean isKF8 = false;
|
||||
Charset charset = StandardCharsets.UTF_8;
|
||||
Map<Integer, String> exthData = new HashMap<>();
|
||||
Map<Integer, Integer> exthRecords = new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MobiMetadataExtractor extends MobiBaseMetadataExtractor {
|
||||
|
||||
@Override
|
||||
protected String getFormatName() {
|
||||
return "MOBI";
|
||||
}
|
||||
}
|
||||
+10
-9
@@ -8,18 +8,17 @@ import com.adityachandel.booklore.model.enums.OpdsSortOrder;
|
||||
import com.adityachandel.booklore.service.MagicShelfService;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -381,7 +380,7 @@ public class OpdsFeedService {
|
||||
int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE);
|
||||
|
||||
Page<Book> booksPage = opdsBookService.getRecentBooksPage(userId, page - 1, size);
|
||||
|
||||
|
||||
// Apply user's preferred sort order
|
||||
booksPage = opdsBookService.applySortOrder(booksPage, sortOrder);
|
||||
|
||||
@@ -621,6 +620,8 @@ public class OpdsFeedService {
|
||||
}
|
||||
yield "application/x-fictionbook+xml";
|
||||
}
|
||||
case MOBI -> "application/x-mobipocket-ebook";
|
||||
case AZW3 -> "application/vnd.amazon.ebook";
|
||||
case CBX -> {
|
||||
if (book.getArchiveType() != null) {
|
||||
yield switch (book.getArchiveType()) {
|
||||
@@ -674,9 +675,9 @@ public class OpdsFeedService {
|
||||
private Set<Long> parseShelfIds(HttpServletRequest request) {
|
||||
String shelfIdParam = request.getParameter("shelfId");
|
||||
String shelfIdsParam = request.getParameter("shelfIds");
|
||||
|
||||
|
||||
Set<Long> shelfIds = new HashSet<>();
|
||||
|
||||
|
||||
// Support both single shelfId and comma-separated shelfIds
|
||||
if (shelfIdParam != null && !shelfIdParam.isBlank()) {
|
||||
try {
|
||||
@@ -685,7 +686,7 @@ public class OpdsFeedService {
|
||||
log.warn("Invalid shelfId parameter: {}", shelfIdParam);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (shelfIdsParam != null && !shelfIdsParam.isBlank()) {
|
||||
for (String id : shelfIdsParam.split(",")) {
|
||||
try {
|
||||
@@ -695,7 +696,7 @@ public class OpdsFeedService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return shelfIds.isEmpty() ? null : shelfIds;
|
||||
}
|
||||
|
||||
|
||||
+19
@@ -24,6 +24,7 @@ public class DefaultUserSettingsProvider {
|
||||
defaultSettings.put(UserSettingKey.PER_BOOK_SETTING, this::buildDefaultPerBookSetting);
|
||||
defaultSettings.put(UserSettingKey.PDF_READER_SETTING, this::buildDefaultPdfReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.EPUB_READER_SETTING, this::buildDefaultEpubReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.EBOOK_READER_SETTING, this::buildDefaultEbookReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.CBX_READER_SETTING, this::buildDefaultCbxReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.NEW_PDF_READER_SETTING, this::buildDefaultNewPdfReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.SIDEBAR_LIBRARY_SORTING, this::buildDefaultSidebarLibrarySorting);
|
||||
@@ -75,6 +76,23 @@ public class DefaultUserSettingsProvider {
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookLoreUser.UserSettings.EbookReaderSetting buildDefaultEbookReaderSetting() {
|
||||
return BookLoreUser.UserSettings.EbookReaderSetting.builder()
|
||||
.fontFamily("serif")
|
||||
.fontSize(16)
|
||||
.gap(0.05f)
|
||||
.hyphenate(false)
|
||||
.isDark(false)
|
||||
.justify(false)
|
||||
.lineHeight(1.5f)
|
||||
.maxBlockSize(1440)
|
||||
.maxColumnCount(2)
|
||||
.maxInlineSize(720)
|
||||
.theme("gray")
|
||||
.flow("paginated")
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookLoreUser.UserSettings.CbxReaderSetting buildDefaultCbxReaderSetting() {
|
||||
return BookLoreUser.UserSettings.CbxReaderSetting.builder()
|
||||
.pageViewMode(CbxPageViewMode.SINGLE_PAGE)
|
||||
@@ -112,6 +130,7 @@ public class DefaultUserSettingsProvider {
|
||||
.view("GRID")
|
||||
.coverSize(1.0F)
|
||||
.seriesCollapsed(false)
|
||||
.overlayBookType(true)
|
||||
.build())
|
||||
.overrides(null)
|
||||
.build();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.progress.*;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
|
||||
public class BookProgressUtil {
|
||||
|
||||
public static void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(KoboProgress.builder()
|
||||
.percentage(progress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
BookFileType type = book.getBookType();
|
||||
if (type == null) return;
|
||||
|
||||
switch (type) {
|
||||
case EPUB -> {
|
||||
book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.href(progress.getEpubProgressHref())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
book.setKoreaderProgress(KoProgress.builder()
|
||||
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
|
||||
.build());
|
||||
}
|
||||
case FB2, MOBI, AZW3 -> book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.href(progress.getEpubProgressHref())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
public static void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
book.setPersonalRating(progress.getPersonalRating());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
CREATE TABLE IF NOT EXISTS ebook_viewer_preference
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
font_family VARCHAR(128) NULL,
|
||||
font_size INT NULL,
|
||||
gap FLOAT NULL,
|
||||
hyphenate BOOLEAN NULL,
|
||||
is_dark BOOLEAN NULL,
|
||||
justify BOOLEAN NULL,
|
||||
line_height FLOAT NULL,
|
||||
max_block_size INT NULL,
|
||||
max_column_count INT NULL,
|
||||
max_inline_size INT NULL,
|
||||
theme VARCHAR(64) NULL,
|
||||
flow VARCHAR(32) NULL,
|
||||
UNIQUE (user_id, book_id),
|
||||
CONSTRAINT fk_ebook_viewer_preference_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ebook_viewer_preference_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
ALTER TABLE user_book_progress
|
||||
ADD COLUMN IF NOT EXISTS epub_progress_href VARCHAR(1000);
|
||||
@@ -38,7 +38,7 @@ class BookServiceDeleteTests {
|
||||
void setUp() {
|
||||
BookRepository bookRepository = Mockito.mock(BookRepository.class);
|
||||
PdfViewerPreferencesRepository pdfViewerPreferencesRepository = Mockito.mock(PdfViewerPreferencesRepository.class);
|
||||
EpubViewerPreferencesRepository epubViewerPreferencesRepository = Mockito.mock(EpubViewerPreferencesRepository.class);
|
||||
EbookViewerPreferenceRepository ebookViewerPreferenceRepository = Mockito.mock(EbookViewerPreferenceRepository.class);
|
||||
CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class);
|
||||
NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository = Mockito.mock(NewPdfViewerPreferencesRepository.class);
|
||||
FileService fileService = Mockito.mock(FileService.class);
|
||||
@@ -54,7 +54,6 @@ class BookServiceDeleteTests {
|
||||
bookService = new BookService(
|
||||
bookRepository,
|
||||
pdfViewerPreferencesRepository,
|
||||
epubViewerPreferencesRepository,
|
||||
cbxViewerPreferencesRepository,
|
||||
newPdfViewerPreferencesRepository,
|
||||
fileService,
|
||||
@@ -65,7 +64,8 @@ class BookServiceDeleteTests {
|
||||
userProgressService,
|
||||
bookDownloadService,
|
||||
monitoringRegistrationService,
|
||||
bookUpdateService
|
||||
bookUpdateService,
|
||||
ebookViewerPreferenceRepository
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+28
-7
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -38,7 +39,7 @@ import java.util.Set;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class)
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookServiceTest {
|
||||
|
||||
@Mock
|
||||
@@ -46,7 +47,7 @@ class BookServiceTest {
|
||||
@Mock
|
||||
private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
@Mock
|
||||
private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
@Mock
|
||||
private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@Mock
|
||||
@@ -170,15 +171,35 @@ class BookServiceTest {
|
||||
primaryFile.setBookType(BookFileType.EPUB);
|
||||
entity.setBookFiles(List.of(primaryFile));
|
||||
when(bookRepository.findByIdWithBookFiles(4L)).thenReturn(Optional.of(entity));
|
||||
EpubViewerPreferencesEntity epubPref = new EpubViewerPreferencesEntity();
|
||||
epubPref.setFont("Arial");
|
||||
when(epubViewerPreferencesRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref));
|
||||
EbookViewerPreferenceEntity epubPref = new EbookViewerPreferenceEntity();
|
||||
epubPref.setFontFamily("Arial");
|
||||
epubPref.setFontSize(16);
|
||||
epubPref.setGap(0.2f);
|
||||
epubPref.setHyphenate(true);
|
||||
epubPref.setIsDark(false);
|
||||
epubPref.setJustify(true);
|
||||
epubPref.setLineHeight(1.5f);
|
||||
epubPref.setMaxBlockSize(800);
|
||||
epubPref.setMaxColumnCount(2);
|
||||
epubPref.setMaxInlineSize(1200);
|
||||
epubPref.setTheme("light");
|
||||
when(ebookViewerPreferenceRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref));
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
BookViewerSettings settings = bookService.getBookViewerSetting(4L);
|
||||
|
||||
assertNotNull(settings.getEpubSettings());
|
||||
assertEquals("Arial", settings.getEpubSettings().getFont());
|
||||
assertNotNull(settings.getEbookSettings());
|
||||
assertEquals("Arial", settings.getEbookSettings().getFontFamily());
|
||||
assertEquals(16, settings.getEbookSettings().getFontSize());
|
||||
assertEquals(0.2f, settings.getEbookSettings().getGap());
|
||||
assertTrue(settings.getEbookSettings().getHyphenate());
|
||||
assertFalse(settings.getEbookSettings().getIsDark());
|
||||
assertTrue(settings.getEbookSettings().getJustify());
|
||||
assertEquals(1.5f, settings.getEbookSettings().getLineHeight());
|
||||
assertEquals(800, settings.getEbookSettings().getMaxBlockSize());
|
||||
assertEquals(2, settings.getEbookSettings().getMaxColumnCount());
|
||||
assertEquals(1200, settings.getEbookSettings().getMaxInlineSize());
|
||||
assertEquals("light", settings.getEbookSettings().getTheme());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+33
-23
@@ -34,8 +34,6 @@ class BookUpdateServiceTest {
|
||||
@Mock
|
||||
private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
@Mock
|
||||
private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
@Mock
|
||||
private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@Mock
|
||||
private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
@@ -55,6 +53,8 @@ class BookUpdateServiceTest {
|
||||
private UserProgressService userProgressService;
|
||||
@Mock
|
||||
private KoboReadingStateService koboReadingStateService;
|
||||
@Mock
|
||||
private EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
|
||||
@InjectMocks
|
||||
private BookUpdateService bookUpdateService;
|
||||
@@ -65,7 +65,6 @@ class BookUpdateServiceTest {
|
||||
bookUpdateService = new BookUpdateService(
|
||||
bookRepository,
|
||||
pdfViewerPreferencesRepository,
|
||||
epubViewerPreferencesRepository,
|
||||
cbxViewerPreferencesRepository,
|
||||
newPdfViewerPreferencesRepository,
|
||||
shelfRepository,
|
||||
@@ -75,7 +74,8 @@ class BookUpdateServiceTest {
|
||||
authenticationService,
|
||||
bookQueryService,
|
||||
userProgressService,
|
||||
koboReadingStateService
|
||||
koboReadingStateService,
|
||||
ebookViewerPreferenceRepository
|
||||
);
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ class BookUpdateServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateBookViewerSetting_epub_shouldUpdateEpubPrefs() {
|
||||
void updateBookViewerSetting_epub_shouldUpdateEpubPrefsV2() {
|
||||
long bookId = 1L;
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(bookId);
|
||||
@@ -123,30 +123,40 @@ class BookUpdateServiceTest {
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(2L);
|
||||
|
||||
EpubViewerPreferencesEntity epubPrefs = new EpubViewerPreferencesEntity();
|
||||
when(epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(epubPrefs));
|
||||
EbookViewerPreferenceEntity epubPrefs = new EbookViewerPreferenceEntity();
|
||||
when(ebookViewerPreferenceRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(epubPrefs));
|
||||
BookViewerSettings settings = BookViewerSettings.builder()
|
||||
.epubSettings(EpubViewerPreferences.builder()
|
||||
.font("font")
|
||||
.fontSize(12)
|
||||
.theme("theme")
|
||||
.flow("flow")
|
||||
.spread("spread")
|
||||
.letterSpacing(1.2f)
|
||||
.lineHeight(1.3f)
|
||||
.ebookSettings(EbookViewerPreferences.builder()
|
||||
.fontFamily("serif")
|
||||
.fontSize(18)
|
||||
.gap(0.1f)
|
||||
.hyphenate(true)
|
||||
.isDark(true)
|
||||
.justify(true)
|
||||
.lineHeight(1.7f)
|
||||
.maxBlockSize(800)
|
||||
.maxColumnCount(3)
|
||||
.maxInlineSize(1200)
|
||||
.theme("dark")
|
||||
.flow("paginated")
|
||||
.build())
|
||||
.build();
|
||||
|
||||
bookUpdateService.updateBookViewerSetting(bookId, settings);
|
||||
|
||||
verify(epubViewerPreferencesRepository).save(epubPrefs);
|
||||
assertEquals("font", epubPrefs.getFont());
|
||||
assertEquals(12, epubPrefs.getFontSize());
|
||||
assertEquals("theme", epubPrefs.getTheme());
|
||||
assertEquals("flow", epubPrefs.getFlow());
|
||||
assertEquals("spread", epubPrefs.getSpread());
|
||||
assertEquals(1.2f, epubPrefs.getLetterSpacing());
|
||||
assertEquals(1.3f, epubPrefs.getLineHeight());
|
||||
verify(ebookViewerPreferenceRepository).save(epubPrefs);
|
||||
assertEquals("serif", epubPrefs.getFontFamily());
|
||||
assertEquals(18, epubPrefs.getFontSize());
|
||||
assertEquals(0.1f, epubPrefs.getGap());
|
||||
assertTrue(epubPrefs.getHyphenate());
|
||||
assertTrue(epubPrefs.getIsDark());
|
||||
assertTrue(epubPrefs.getJustify());
|
||||
assertEquals(1.7f, epubPrefs.getLineHeight());
|
||||
assertEquals(800, epubPrefs.getMaxBlockSize());
|
||||
assertEquals(3, epubPrefs.getMaxColumnCount());
|
||||
assertEquals(1200, epubPrefs.getMaxInlineSize());
|
||||
assertEquals("dark", epubPrefs.getTheme());
|
||||
assertEquals("paginated", epubPrefs.getFlow());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -42,6 +42,11 @@
|
||||
"glob": "**/*",
|
||||
"input": "node_modules/ngx-extended-pdf-viewer/assets/",
|
||||
"output": "/assets/"
|
||||
},
|
||||
{
|
||||
"glob": "**/*",
|
||||
"input": "libs/foliate-js",
|
||||
"output": "/assets/foliate/"
|
||||
}
|
||||
],
|
||||
"styles": [
|
||||
|
||||
@@ -25,6 +25,7 @@ import {BookdropGuard} from './core/security/guards/bookdrop.guard';
|
||||
import {LibraryStatsGuard} from './core/security/guards/library-stats.guard';
|
||||
import {UserStatsGuard} from './core/security/guards/user-stats.guard';
|
||||
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
|
||||
import {EbookReaderComponent} from './features/readers/ebook-reader/ebook-reader.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
@@ -68,6 +69,11 @@ export const routes: Routes = [
|
||||
component: EpubReaderComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'ebook-reader/book/:bookId',
|
||||
component: EbookReaderComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'cbx-reader/book/:bookId',
|
||||
component: CbxReaderComponent,
|
||||
|
||||
+12
-1
@@ -124,6 +124,16 @@
|
||||
{{ coverScalePreferenceService.scaleFactor.toFixed(2) }}x
|
||||
</div>
|
||||
</div>
|
||||
<!-- Book type pill toggle control -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="show-book-type-pill-checkbox" class="font-medium">Show book type pill</label>
|
||||
<p-checkbox
|
||||
inputId="show-book-type-pill-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill"
|
||||
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
|
||||
</p-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
@@ -273,7 +283,8 @@
|
||||
[onBookSelect]="handleBookSelect.bind(this)"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="selectedBooks.has(book.id)">
|
||||
[isSelected]="selectedBooks.has(book.id)"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ import {TaskHelperService} from '../../../settings/task-management/task-helper.s
|
||||
import {FilterLabelHelper} from './filter-label.helper';
|
||||
import {LoadingService} from '../../../../core/services/loading.service';
|
||||
import {BookNavigationService} from '../../service/book-navigation.service';
|
||||
import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service';
|
||||
|
||||
export enum EntityType {
|
||||
LIBRARY = 'Library',
|
||||
@@ -123,6 +124,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
private pageTitle = inject(PageTitleService);
|
||||
private loadingService = inject(LoadingService);
|
||||
private bookNavigationService = inject(BookNavigationService);
|
||||
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
|
||||
|
||||
bookState$: Observable<BookState> | undefined;
|
||||
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, Subject} from 'rxjs';
|
||||
import {debounceTime, filter, takeUntil} from 'rxjs/operators';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookCardOverlayPreferenceService {
|
||||
private readonly userService = inject(UserService);
|
||||
|
||||
private readonly _showBookTypePill = new BehaviorSubject<boolean>(true);
|
||||
readonly showBookTypePill$ = this._showBookTypePill.asObservable();
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private hasUserToggled = false;
|
||||
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
|
||||
|
||||
constructor() {
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(() => {
|
||||
this.loadPreferencesFromUser();
|
||||
});
|
||||
|
||||
this.showBookTypePill$
|
||||
.pipe(debounceTime(500))
|
||||
.subscribe(show => {
|
||||
if (this.hasUserToggled) {
|
||||
this.persistPreference(show);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setShowBookTypePill(show: boolean): void {
|
||||
this.hasUserToggled = true;
|
||||
this._showBookTypePill.next(show);
|
||||
}
|
||||
|
||||
get showBookTypePill(): boolean {
|
||||
return this._showBookTypePill.value;
|
||||
}
|
||||
|
||||
private loadPreferencesFromUser(): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const prefs = user?.userSettings?.entityViewPreferences;
|
||||
|
||||
let show = true;
|
||||
if (prefs) {
|
||||
const globalAny = prefs.global as any;
|
||||
show = prefs.global?.overlayBookType ?? globalAny?.showBookTypePill ?? true;
|
||||
|
||||
if (this.currentContext) {
|
||||
const override = prefs.overrides?.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
if (override) {
|
||||
const prefAny = override.preferences as any;
|
||||
if (override.preferences.overlayBookType !== undefined) {
|
||||
show = override.preferences.overlayBookType;
|
||||
} else if (prefAny?.showBookTypePill !== undefined) {
|
||||
show = prefAny.showBookTypePill;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.hasUserToggled = false;
|
||||
if (this._showBookTypePill.value !== show) {
|
||||
this._showBookTypePill.next(show);
|
||||
}
|
||||
}
|
||||
|
||||
private persistPreference(show: boolean): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
if (!user) return;
|
||||
|
||||
const prefs = structuredClone(user.userSettings.entityViewPreferences ?? {
|
||||
global: {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'DESC',
|
||||
view: 'GRID',
|
||||
coverSize: 1.0,
|
||||
seriesCollapsed: false,
|
||||
overlayBookType: true
|
||||
},
|
||||
overrides: []
|
||||
});
|
||||
|
||||
if (!prefs.overrides) {
|
||||
prefs.overrides = [];
|
||||
}
|
||||
|
||||
if (this.currentContext) {
|
||||
let override = prefs.overrides.find(o =>
|
||||
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
|
||||
);
|
||||
|
||||
if (!override) {
|
||||
override = {
|
||||
entityType: this.currentContext.type,
|
||||
entityId: this.currentContext.id,
|
||||
preferences: {
|
||||
...prefs.global,
|
||||
overlayBookType: show
|
||||
}
|
||||
};
|
||||
prefs.overrides.push(override);
|
||||
} else {
|
||||
override.preferences.overlayBookType = show;
|
||||
}
|
||||
} else {
|
||||
prefs.global.overlayBookType = show;
|
||||
}
|
||||
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
+18
-12
@@ -12,17 +12,23 @@
|
||||
decoding="async"
|
||||
(load)="onImageLoad()"/>
|
||||
|
||||
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
|
||||
<div class="series-number-overlay">
|
||||
#{{ book.metadata?.seriesNumber }}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (book.seriesCount && book.seriesCount >= 1) {
|
||||
<div class="series-items-count-overlay" [pTooltip]="seriesCountTooltip" tooltipPosition="right">
|
||||
<i class="pi pi-book" style="font-size: 0.65rem; margin-right: 2px;"></i>{{ book.seriesCount }}
|
||||
</div>
|
||||
}
|
||||
<div class="top-left-overlay-stack">
|
||||
@if (showBookTypePill && book.bookType) {
|
||||
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + book.bookType.toLowerCase()">
|
||||
{{ book.bookType }}
|
||||
</div>
|
||||
}
|
||||
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
|
||||
<div class="series-number-overlay">
|
||||
#{{ book.metadata?.seriesNumber }}
|
||||
</div>
|
||||
}
|
||||
@if (book.seriesCount && book.seriesCount >= 1) {
|
||||
<div class="series-items-count-overlay">
|
||||
<i class="pi pi-book series-items-count-icon"></i>{{ book.seriesCount }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (_isSeriesViewActive) {
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openSeriesInfo()"></p-button>
|
||||
@@ -30,7 +36,7 @@
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)"></p-button>
|
||||
}
|
||||
|
||||
@if (!_isSeriesViewActive && _canReadBook) {
|
||||
@if (!_isSeriesViewActive) {
|
||||
<p-button [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
|
||||
}
|
||||
|
||||
|
||||
+73
-9
@@ -21,10 +21,6 @@
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.cover-container.loaded {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -157,13 +153,11 @@
|
||||
|
||||
.series-items-count-overlay {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
background-color: var(--primary-color);
|
||||
color: var(--primary-text-color-dark);
|
||||
font-size: 0.75rem;
|
||||
padding: 3px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.7rem;
|
||||
padding: 0 5px;
|
||||
border-radius: 6px;
|
||||
z-index: 3;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
@@ -176,6 +170,76 @@
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.series-items-count-icon {
|
||||
font-size: 0.6rem;
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
.book-type-pill-overlay {
|
||||
position: absolute;
|
||||
background: var(--primary-color, #6366f1);
|
||||
color: var(--primary-text-color-dark, #fff);
|
||||
font-size: 0.675rem;
|
||||
font-weight: 700;
|
||||
padding: 1px 6px;
|
||||
border-radius: 6px;
|
||||
z-index: 3;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
|
||||
letter-spacing: 0.03em;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
text-transform: uppercase;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.top-left-overlay-stack {
|
||||
position: absolute;
|
||||
top: 7px;
|
||||
left: 7px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
z-index: 4;
|
||||
}
|
||||
|
||||
.book-type-pill-overlay,
|
||||
.series-number-overlay,
|
||||
.series-items-count-overlay {
|
||||
position: static;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.book-type-epub {
|
||||
background: #16a34a; /* medium green */
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-pdf {
|
||||
background: #dc2626; /* medium red */
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cbx {
|
||||
background: #d97706; /* amber/orange */
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-mobi {
|
||||
background: #2563eb; /* medium blue */
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-azw3 {
|
||||
background: #0891b2; /* cyan/teal */
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-fb2 {
|
||||
background: #7c3aed; /* vibrant purple */
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.read-status-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+16
-2
@@ -23,6 +23,7 @@ import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card',
|
||||
@@ -45,6 +46,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
@Input() bottomBarHidden: boolean = false;
|
||||
@Input() seriesViewEnabled: boolean = false;
|
||||
@Input() isSeriesCollapsed: boolean = false;
|
||||
@Input() overlayPreferenceService?: BookCardOverlayPreferenceService;
|
||||
|
||||
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
|
||||
|
||||
@@ -69,7 +71,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
protected _koProgressPercentage: number | null = null;
|
||||
protected _koboProgressPercentage: number | null = null;
|
||||
protected _displayTitle: string | undefined = undefined;
|
||||
protected _canReadBook: boolean = true;
|
||||
protected _isSeriesViewActive: boolean = false;
|
||||
protected _coverImageUrl: string = '';
|
||||
protected _readStatusIcon: string = '';
|
||||
@@ -86,6 +87,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
private user: User | null = null;
|
||||
private menuInitialized = false;
|
||||
|
||||
showBookTypePill = true;
|
||||
|
||||
private overlayPrefSub?: any;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.computeAllMemoizedValues();
|
||||
this.userService.userState$
|
||||
@@ -98,6 +103,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
this.user = userState.user;
|
||||
this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route';
|
||||
});
|
||||
|
||||
if (this.overlayPreferenceService) {
|
||||
this.overlayPrefSub = this.overlayPreferenceService.showBookTypePill$.subscribe(val => {
|
||||
this.showBookTypePill = val;
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
@@ -131,7 +143,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName)
|
||||
? this.book.metadata?.seriesName
|
||||
: this.book.metadata?.title;
|
||||
this._canReadBook = this.book?.bookType !== 'FB2';
|
||||
this._coverImageUrl = this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
|
||||
|
||||
this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus);
|
||||
@@ -770,5 +781,8 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
if (this.overlayPrefSub) {
|
||||
this.overlayPrefSub.unsubscribe();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrol
|
||||
import {BookReview} from '../components/book-reviews/book-review-service';
|
||||
import {ZoomType} from 'ngx-extended-pdf-viewer';
|
||||
|
||||
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2";
|
||||
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3";
|
||||
|
||||
export enum AdditionalFileType {
|
||||
ALTERNATIVE_FORMAT = 'ALTERNATIVE_FORMAT',
|
||||
@@ -48,6 +48,7 @@ export interface Book extends FileInfo {
|
||||
libraryPath?: { id: number };
|
||||
alternativeFormats?: AdditionalFile[];
|
||||
supplementaryFiles?: AdditionalFile[];
|
||||
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -150,6 +151,7 @@ export interface BookMetadata {
|
||||
tagsLocked?: boolean;
|
||||
coverLocked?: boolean;
|
||||
reviewsLocked?: boolean;
|
||||
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -210,6 +212,21 @@ export interface EpubViewerSetting {
|
||||
customFontId?: number | null;
|
||||
}
|
||||
|
||||
export interface EbookViewerSetting {
|
||||
lineHeight: number;
|
||||
justify: boolean;
|
||||
hyphenate: boolean;
|
||||
maxColumnCount: number;
|
||||
gap: number;
|
||||
fontSize: number;
|
||||
theme: string
|
||||
maxInlineSize: number;
|
||||
maxBlockSize: number;
|
||||
fontFamily: string | null;
|
||||
isDark: boolean;
|
||||
flow: 'paginated' | 'scrolled';
|
||||
}
|
||||
|
||||
export interface CbxViewerSetting {
|
||||
pageSpread: CbxPageSpread;
|
||||
pageViewMode: CbxPageViewMode;
|
||||
@@ -221,8 +238,10 @@ export interface CbxViewerSetting {
|
||||
export interface BookSetting {
|
||||
pdfSettings?: PdfViewerSetting;
|
||||
epubSettings?: EpubViewerSetting;
|
||||
ebookSettings?: EbookViewerSetting;
|
||||
cbxSettings?: CbxViewerSetting;
|
||||
newPdfSettings?: NewPdfReaderSetting;
|
||||
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {SortOption} from './sort.model';
|
||||
|
||||
export type LibraryScanMode = 'FILE_AS_BOOK' | 'FOLDER_AS_BOOK';
|
||||
export type BookFileType = 'PDF' | 'EPUB' | 'CBX' | 'FB2';
|
||||
export type BookFileType = 'PDF' | 'EPUB' | 'CBX' | 'FB2' | 'MOBI' | 'AZW3';
|
||||
|
||||
export interface Library {
|
||||
id?: number;
|
||||
|
||||
@@ -68,12 +68,10 @@ describe('BookPatchService', () => {
|
||||
|
||||
it('should save EPUB progress', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
service.saveEpubProgress(2, 'cfi123', 0.8).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 2,
|
||||
epubProgress: {cfi: 'cfi123', percentage: 0.8}
|
||||
});
|
||||
service.saveEpubProgress(2, 'cfi123', 'href123', 0.8);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 2,
|
||||
epubProgress: {cfi: 'cfi123', href: 'href123', percentage: 0.8}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {tap} from 'rxjs/operators';
|
||||
import {Observable, Subject} from 'rxjs';
|
||||
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
|
||||
import {Book, ReadStatus} from '../model/book.model';
|
||||
import {BookStateService} from './book-state.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
@@ -17,6 +17,33 @@ export class BookPatchService {
|
||||
private http = inject(HttpClient);
|
||||
private bookStateService = inject(BookStateService);
|
||||
|
||||
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number }>();
|
||||
|
||||
private epubProgress$ = this.epubProgressSubject.pipe(
|
||||
distinctUntilChanged((prev, curr) =>
|
||||
prev.bookId === curr.bookId &&
|
||||
prev.cfi === curr.cfi &&
|
||||
prev.href === curr.href &&
|
||||
prev.percentage === curr.percentage
|
||||
),
|
||||
exhaustMap(payload => {
|
||||
const body = {
|
||||
bookId: payload.bookId,
|
||||
epubProgress: {
|
||||
cfi: payload.cfi,
|
||||
href: payload.href,
|
||||
percentage: payload.percentage
|
||||
}
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}),
|
||||
share()
|
||||
);
|
||||
|
||||
constructor() {
|
||||
this.epubProgress$.subscribe();
|
||||
}
|
||||
|
||||
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
|
||||
const requestPayload = {
|
||||
bookIds: Array.from(bookIds),
|
||||
@@ -49,15 +76,8 @@ export class BookPatchService {
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
epubProgress: {
|
||||
cfi: cfi,
|
||||
percentage: percentage
|
||||
}
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): void {
|
||||
this.epubProgressSubject.next({bookId, cfi, href, percentage});
|
||||
}
|
||||
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
@@ -197,4 +217,3 @@ export class BookPatchService {
|
||||
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -329,12 +329,6 @@ describe('BookService', () => {
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should save epub progress', async () => {
|
||||
bookPatchServiceMock.saveEpubProgress.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.saveEpubProgress(1, 'cfi', 0.5));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should save cbx progress', async () => {
|
||||
bookPatchServiceMock.saveCbxProgress.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.saveCbxProgress(1, 2, 0.5));
|
||||
|
||||
@@ -259,8 +259,8 @@ export class BookService {
|
||||
? reader === 'ngx'
|
||||
? 'pdf-reader'
|
||||
: 'cbx-reader'
|
||||
: book.bookType === 'EPUB'
|
||||
? 'epub-reader'
|
||||
: book.bookType === 'EPUB' || book.bookType === 'FB2' || book.bookType === 'MOBI' || book.bookType === 'AZW3'
|
||||
? 'ebook-reader'
|
||||
: book.bookType === 'CBX'
|
||||
? 'cbx-reader'
|
||||
: null;
|
||||
@@ -414,9 +414,9 @@ export class BookService {
|
||||
return this.bookPatchService.savePdfProgress(bookId, page, percentage);
|
||||
}
|
||||
|
||||
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
|
||||
return this.bookPatchService.saveEpubProgress(bookId, cfi, percentage);
|
||||
}
|
||||
/*saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): Observable<void> {
|
||||
return this.bookPatchService.saveEpubProgress(bookId, cfi, href, percentage);
|
||||
}*/
|
||||
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
return this.bookPatchService.saveCbxProgress(bookId, page, percentage);
|
||||
|
||||
+6
-1
@@ -24,7 +24,12 @@
|
||||
[horizontal]="true">
|
||||
@for (book of books; track book.id) {
|
||||
<div class="dashboard-scroller-card" [class.menu-open]="openMenuBookId === book.id">
|
||||
<app-book-card [book]="book" [isCheckboxEnabled]="false" (menuToggled)="handleMenuToggle(book.id, $event)"></app-book-card>
|
||||
<app-book-card
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="false"
|
||||
(menuToggled)="handleMenuToggle(book.id, $event)"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService"
|
||||
></app-book-card>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
+4
-1
@@ -1,10 +1,11 @@
|
||||
import {Component, ElementRef, Input, ViewChild} from '@angular/core';
|
||||
import {Component, ElementRef, Input, ViewChild, inject} from '@angular/core';
|
||||
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
|
||||
import {ProgressSpinnerModule} from 'primeng/progressspinner';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {ScrollerType} from '../../models/dashboard-config.model';
|
||||
import { BookCardOverlayPreferenceService } from '../../../book/components/book-browser/book-card-overlay-preference.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-dashboard-scroller',
|
||||
@@ -27,6 +28,8 @@ export class DashboardScrollerComponent {
|
||||
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
|
||||
openMenuBookId: number | null = null;
|
||||
|
||||
public bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
|
||||
|
||||
handleMenuToggle(bookId: number, isOpen: boolean) {
|
||||
this.openMenuBookId = isOpen ? bookId : null;
|
||||
}
|
||||
|
||||
@@ -197,7 +197,10 @@ export class MagicShelfComponent implements OnInit {
|
||||
{label: 'EPUB', value: 'epub'},
|
||||
{label: 'CBR', value: 'cbr'},
|
||||
{label: 'CBZ', value: 'cbz'},
|
||||
{label: 'CB7', value: 'cb7'}
|
||||
{label: 'CB7', value: 'cb7'},
|
||||
{label: 'FB2', value: 'fb2'},
|
||||
{label: 'MOBI', value: 'mobi'},
|
||||
{label: 'AZW3', value: 'azw3'}
|
||||
];
|
||||
|
||||
readStatusOptions = Object.entries(ReadStatus).map(([key, value]) => ({
|
||||
|
||||
+1
-1
@@ -559,7 +559,7 @@
|
||||
<p-splitbutton label="Read" icon="pi pi-book" [model]="readItems" (onClick)="read(book.id, 'ngx')" severity="primary"/>
|
||||
}
|
||||
}
|
||||
@if (book!.bookType !== 'PDF' && book!.bookType !== 'FB2') {
|
||||
@if (book!.bookType !== 'PDF') {
|
||||
<p-button label="Read" icon="pi pi-book" (onClick)="read(book?.metadata!.bookId, undefined)" severity="primary"/>
|
||||
}
|
||||
<p-button label="Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(book.id)" class="mobile-icon-only"></p-button>
|
||||
|
||||
+6
@@ -734,6 +734,12 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
return 'purple';
|
||||
case 'cb7':
|
||||
return 'blue';
|
||||
case 'fb2':
|
||||
return 'orange';
|
||||
case 'mobi':
|
||||
return 'yellow';
|
||||
case 'azw3':
|
||||
return 'green';
|
||||
default:
|
||||
return 'gray';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<div
|
||||
class="reader"
|
||||
[style.background-color]="stateService.currentState.theme.bg ?? ''">
|
||||
|
||||
@if (isLoading) {
|
||||
<div class="loader-overlay">
|
||||
<div class="loader-content">
|
||||
<div class="spinner"></div>
|
||||
<p class="loader-text">Loading book...</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<app-reader-header
|
||||
[bookTitle]="book?.metadata?.title!"
|
||||
[currentTheme]="stateService.currentState.theme"
|
||||
[isDark]="stateService.currentState.isDark"
|
||||
[fontSize]="stateService.currentState.fontSize"
|
||||
[lineHeight]="stateService.currentState.lineHeight"
|
||||
[forceVisible]="forceHeaderVisible"
|
||||
[flow]="stateService.currentState.flow"
|
||||
(setFlow)="onSetFlow($event)"
|
||||
(showChapters)="showChapters = true"
|
||||
(showControls)="showControls = true"
|
||||
(showMetadata)="showMetadata = true"
|
||||
(createBookmark)="onCreateBookmark()"
|
||||
(close)="location.back()"
|
||||
(toggleDarkMode)="onToggleDarkMode()"
|
||||
(increaseFontSize)="onIncreaseFontSize()"
|
||||
(decreaseFontSize)="onDecreaseFontSize()"
|
||||
(increaseLineHeight)="onIncreaseLineHeight()"
|
||||
(decreaseLineHeight)="onDecreaseLineHeight()"
|
||||
></app-reader-header>
|
||||
|
||||
|
||||
<div class="reader-content" style="position: relative;">
|
||||
@if (isCurrentCfiBookmarked) {
|
||||
<div
|
||||
style="
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 12px;
|
||||
z-index: 10;
|
||||
width: 48px;
|
||||
height: 64px;
|
||||
background: none;
|
||||
pointer-events: none;
|
||||
">
|
||||
<svg width="48" height="64" viewBox="0 0 48 64">
|
||||
<polygon points="0,0 48,0 48,64 24,48 0,64" fill="red"/>
|
||||
</svg>
|
||||
</div>
|
||||
}
|
||||
<div id="foliate-container" tabindex="0"></div>
|
||||
</div>
|
||||
|
||||
<app-reader-navbar
|
||||
[progressData]="currentProgressData"
|
||||
[forceVisible]="forceNavbarVisible"
|
||||
[sectionFractions]="sectionFractions"
|
||||
(progressChange)="onProgressChange($event)">
|
||||
</app-reader-navbar>
|
||||
|
||||
@if (showChapters) {
|
||||
<app-reader-sidebar
|
||||
[bookId]="book?.id ?? null"
|
||||
[coverUpdatedOn]="coverUpdatedOn"
|
||||
[bookTitle]="book?.metadata?.title ?? ''"
|
||||
[bookAuthors]="(book?.metadata?.authors ?? []).join(', ')"
|
||||
[chapters]="chapters"
|
||||
[bookmarks]="bookmarks"
|
||||
[currentChapterHref]="currentChapterHref"
|
||||
(close)="showChapters = false"
|
||||
(chapterClick)="onChapterClick($event)"
|
||||
(bookmarkClick)="onBookmarkClick($event)"
|
||||
(deleteBookmark)="onDeleteBookmark($event)"
|
||||
(coverClick)="showMetadata = true"
|
||||
></app-reader-sidebar>
|
||||
}
|
||||
|
||||
@if (showControls) {
|
||||
<app-settings-dialog
|
||||
[stateService]="stateService"
|
||||
[viewManager]="viewManager"
|
||||
[bookId]="bookId"
|
||||
(close)="showControls = false">
|
||||
</app-settings-dialog>
|
||||
}
|
||||
|
||||
@if (showMetadata) {
|
||||
<app-reader-book-metadata-dialog
|
||||
[book]="book"
|
||||
(close)="showMetadata = false"
|
||||
></app-reader-book-metadata-dialog>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,120 @@
|
||||
.reader {
|
||||
width: 100vw;
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.reader-content {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.navigation-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 10;
|
||||
cursor: pointer;
|
||||
pointer-events: auto;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
#foliate-container {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
::ng-deep foliate-view {
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
display: block !important;
|
||||
position: absolute !important;
|
||||
top: 0 !important;
|
||||
left: 0 !important;
|
||||
}
|
||||
|
||||
.loader-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.loader-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border: 4px solid rgba(255, 255, 255, 0.2);
|
||||
border-top-color: #fff;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.loader-text {
|
||||
color: #fff;
|
||||
font-size: 1.1rem;
|
||||
margin: 0;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
foliate-view::part(head) {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 8px 16px;
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-secondary, #666);
|
||||
border-bottom: 1px solid var(--border-color, #e0e0e0);
|
||||
font-family: inherit;
|
||||
min-height: 32px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
foliate-view::part(foot) {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 8px 16px;
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-secondary, #666);
|
||||
border-top: 1px solid var(--border-color, #e0e0e0);
|
||||
font-family: inherit;
|
||||
min-height: 32px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
import {Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule, Location} from '@angular/common';
|
||||
import {forkJoin, Observable, of, Subject, throwError} from 'rxjs';
|
||||
import {catchError, switchMap, takeUntil, tap} from 'rxjs/operators';
|
||||
import {ReaderLoaderService} from './services/reader-loader.service';
|
||||
import {ReaderViewManagerService} from './services/reader-view-manager.service';
|
||||
import {ReaderStateService} from './services/reader-state.service';
|
||||
import {ReaderStyleService} from './services/reader-style.service';
|
||||
import {ReaderBookmarkService} from './services/reader-bookmark.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {BookMark, BookMarkService} from '../../../shared/service/book-mark.service';
|
||||
import {BookPatchService} from '../../book/service/book-patch.service';
|
||||
import {EpubCustomFontService} from '../epub-reader/service/epub-custom-font.service';
|
||||
import {Book, EbookViewerSetting} from '../../book/model/book.model';
|
||||
import {ReaderHeaderComponent} from './reader-layout/header/reader-header.component';
|
||||
import {ReaderSidebarComponent} from './reader-layout/sidebar/reader-sidebar.component';
|
||||
import {ReaderNavbarComponent} from './reader-layout/navbar/reader-navbar.component';
|
||||
import {ReaderSettingsDialogComponent} from './reader-layout/header/reader-settings-dialog.component';
|
||||
import {ReaderBookMetadataDialogComponent} from './reader-layout/sidebar/reader-book-metadata-dialog.component';
|
||||
import {ReadingSessionService} from '../../../shared/service/reading-session.service';
|
||||
import {TocItem} from 'epubjs';
|
||||
import {PageInfo, ThemeInfo} from './utils/reader-header-footer.util';
|
||||
import {ReaderHeaderFooterVisibilityManager} from './utils/reader-header-footer-visibility.util';
|
||||
|
||||
@Component({
|
||||
selector: 'app-ebook-reader',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReaderHeaderComponent,
|
||||
ReaderSettingsDialogComponent,
|
||||
ReaderBookMetadataDialogComponent,
|
||||
ReaderSidebarComponent,
|
||||
ReaderNavbarComponent
|
||||
],
|
||||
schemas: [CUSTOM_ELEMENTS_SCHEMA],
|
||||
providers: [
|
||||
ReaderLoaderService,
|
||||
ReaderViewManagerService,
|
||||
ReaderStateService,
|
||||
ReaderStyleService,
|
||||
ReaderBookmarkService
|
||||
],
|
||||
templateUrl: './ebook-reader.component.html',
|
||||
styleUrls: ['./ebook-reader.component.scss']
|
||||
})
|
||||
export class EbookReaderComponent implements OnInit, OnDestroy {
|
||||
private destroy$ = new Subject<void>();
|
||||
private loaderService = inject(ReaderLoaderService);
|
||||
private styleService = inject(ReaderStyleService);
|
||||
private bookService = inject(BookService);
|
||||
private route = inject(ActivatedRoute);
|
||||
private bookMarkService = inject(BookMarkService);
|
||||
private bookPatchService = inject(BookPatchService);
|
||||
private epubCustomFontService = inject(EpubCustomFontService);
|
||||
private bookmarkService = inject(ReaderBookmarkService);
|
||||
private readingSessionService = inject(ReadingSessionService);
|
||||
|
||||
public viewManager = inject(ReaderViewManagerService);
|
||||
public stateService = inject(ReaderStateService);
|
||||
protected location = inject(Location);
|
||||
protected bookId!: number;
|
||||
|
||||
private hasLoadedOnce = false;
|
||||
private hasStartedSession = false;
|
||||
private _fileUrl: string | null = null;
|
||||
private currentCfi: string | null = null;
|
||||
|
||||
private visibilityManager!: ReaderHeaderFooterVisibilityManager;
|
||||
|
||||
isLoading = true;
|
||||
showControls = false;
|
||||
showChapters = false;
|
||||
showMetadata = false;
|
||||
isCurrentCfiBookmarked = false;
|
||||
forceHeaderVisible = false;
|
||||
forceNavbarVisible = false;
|
||||
|
||||
chapters: TocItem[] = [];
|
||||
bookmarks: BookMark[] = [];
|
||||
book: Book | null = null;
|
||||
coverUpdatedOn: string | undefined;
|
||||
currentChapterName: string | null = null;
|
||||
currentChapterHref: string | null = null;
|
||||
currentProgressData: any = null;
|
||||
private currentPageInfo: PageInfo | undefined;
|
||||
private relocateTimeout: any;
|
||||
private sectionFractionsTimeout: any;
|
||||
|
||||
sectionFractions: number[] = [];
|
||||
|
||||
ngOnInit() {
|
||||
this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight);
|
||||
this.visibilityManager.onStateChange((state) => {
|
||||
this.forceHeaderVisible = state.headerVisible;
|
||||
this.forceNavbarVisible = state.footerVisible;
|
||||
});
|
||||
|
||||
this.isLoading = true;
|
||||
this.initializeFoliate().pipe(
|
||||
switchMap(() => this.epubCustomFontService.loadAndCacheFonts()),
|
||||
tap(() => this.stateService.refreshCustomFonts()),
|
||||
switchMap(() => this.setupView()),
|
||||
switchMap(() => this.loadBookFromAPI()),
|
||||
tap(() => {
|
||||
this.loadBookmarks();
|
||||
this.subscribeToStateChanges();
|
||||
this.subscribeToViewEvents();
|
||||
this.isLoading = false;
|
||||
}),
|
||||
catchError(err => {
|
||||
this.isLoading = false;
|
||||
return of(null);
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
this.viewManager.destroy();
|
||||
this.bookmarkService.reset();
|
||||
this.epubCustomFontService.cleanup();
|
||||
|
||||
if (this.readingSessionService.isSessionActive()) {
|
||||
const progress = typeof this.currentProgressData?.fraction === 'number'
|
||||
? Math.round(this.currentProgressData.fraction * 100 * 100) / 100
|
||||
: undefined;
|
||||
this.readingSessionService.endSession(this.currentCfi || undefined, progress);
|
||||
}
|
||||
|
||||
if (this._fileUrl) {
|
||||
URL.revokeObjectURL(this._fileUrl);
|
||||
this._fileUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
private initializeFoliate(): Observable<void> {
|
||||
return this.loaderService.loadFoliateScript().pipe(
|
||||
switchMap(() => this.loaderService.waitForCustomElement())
|
||||
);
|
||||
}
|
||||
|
||||
private setupView(): Observable<void> {
|
||||
const container = document.getElementById('foliate-container');
|
||||
if (!container) {
|
||||
return throwError(() => new Error('Container not found'));
|
||||
}
|
||||
container.setAttribute('tabindex', '0');
|
||||
this.viewManager.createView(container);
|
||||
return of(undefined);
|
||||
}
|
||||
|
||||
private loadBookFromAPI(): Observable<void> {
|
||||
this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
|
||||
|
||||
return this.stateService.initializeState(this.bookId).pipe(
|
||||
switchMap(() => forkJoin({
|
||||
state: this.stateService.initializeState(this.bookId),
|
||||
book: this.bookService.getBookByIdFromAPI(this.bookId, false),
|
||||
fileBlob: this.bookService.getFileContent(this.bookId)
|
||||
})),
|
||||
switchMap(({book, fileBlob}) => {
|
||||
this.book = book;
|
||||
this.coverUpdatedOn = book.metadata?.coverUpdatedOn;
|
||||
const fileUrl = URL.createObjectURL(fileBlob);
|
||||
this._fileUrl = fileUrl;
|
||||
|
||||
return this.viewManager.loadEpub(fileUrl).pipe(
|
||||
tap(() => {
|
||||
this.applyStyles();
|
||||
this.chapters = this.viewManager.getChapters();
|
||||
}),
|
||||
switchMap(() => this.viewManager.getMetadata()),
|
||||
switchMap(() => {
|
||||
if (!this.hasLoadedOnce) {
|
||||
this.hasLoadedOnce = true;
|
||||
return this.viewManager.goTo(book.epubProgress!.cfi);
|
||||
}
|
||||
return of(undefined);
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private loadBookmarks(): void {
|
||||
this.bookMarkService.getBookmarksForBook(this.bookId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(bookmarks => {
|
||||
this.bookmarks = bookmarks;
|
||||
this.updateIsCurrentCfiBookmarked();
|
||||
});
|
||||
}
|
||||
|
||||
private subscribeToStateChanges(): void {
|
||||
this.stateService.state$
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(() => this.applyStyles());
|
||||
}
|
||||
|
||||
private subscribeToViewEvents(): void {
|
||||
this.viewManager.events$
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(event => {
|
||||
switch (event.type) {
|
||||
case 'load':
|
||||
this.applyStyles();
|
||||
this.chapters = this.viewManager.getChapters();
|
||||
this.updateSectionFractions();
|
||||
break;
|
||||
case 'relocate':
|
||||
if (this.relocateTimeout) clearTimeout(this.relocateTimeout);
|
||||
this.relocateTimeout = setTimeout(() => {
|
||||
this.handleRelocateEvent(event.detail);
|
||||
}, 100);
|
||||
|
||||
if (this.sectionFractionsTimeout) clearTimeout(this.sectionFractionsTimeout);
|
||||
this.sectionFractionsTimeout = setTimeout(() => {
|
||||
this.updateSectionFractions();
|
||||
}, 500);
|
||||
break;
|
||||
case 'middle-single-tap':
|
||||
this.toggleHeaderNavbarPinned();
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private updateSectionFractions(): void {
|
||||
this.sectionFractions = this.viewManager.getSectionFractions();
|
||||
}
|
||||
|
||||
private handleRelocateEvent(detail: any): void {
|
||||
this.currentProgressData = detail;
|
||||
|
||||
const cfi = detail?.cfi ?? null;
|
||||
const href = detail?.pageItem?.href ?? detail?.tocItem?.href ?? null;
|
||||
const percentage = typeof detail?.fraction === 'number' ? detail.fraction * 100 : null;
|
||||
|
||||
if (!this.hasStartedSession && cfi && percentage !== null) {
|
||||
this.hasStartedSession = true;
|
||||
this.readingSessionService.startSession(this.book!.id, this.book?.bookType!, cfi, percentage);
|
||||
}
|
||||
|
||||
if (cfi && percentage !== null) {
|
||||
this.bookPatchService.saveEpubProgress(this.bookId, cfi, href, percentage);
|
||||
this.readingSessionService.updateProgress(cfi, percentage);
|
||||
}
|
||||
|
||||
const chapterLabel = detail?.tocItem?.label;
|
||||
if (chapterLabel && chapterLabel !== this.currentChapterName) {
|
||||
this.currentChapterName = chapterLabel;
|
||||
}
|
||||
|
||||
if (href && href !== this.currentChapterHref) {
|
||||
this.currentChapterHref = href;
|
||||
}
|
||||
|
||||
if (detail?.section) {
|
||||
const percentCompleted = Math.round((detail.fraction * 100) * 10) / 10;
|
||||
const totalMinutes = detail.time?.section ?? 0;
|
||||
|
||||
const hours = Math.floor(totalMinutes / 60);
|
||||
const minutes = Math.floor(totalMinutes % 60);
|
||||
const seconds = Math.round((totalMinutes - Math.floor(totalMinutes)) * 60);
|
||||
|
||||
const parts: string[] = [];
|
||||
if (hours) parts.push(`${hours}h`);
|
||||
if (minutes) parts.push(`${minutes}m`);
|
||||
if (seconds || parts.length === 0) parts.push(`${seconds}s`);
|
||||
|
||||
const sectionTimeText = parts.join(' ');
|
||||
|
||||
this.currentPageInfo = {
|
||||
percentCompleted,
|
||||
sectionTimeText
|
||||
};
|
||||
}
|
||||
|
||||
if (this.stateService.currentState.flow === 'paginated') {
|
||||
const renderer = this.viewManager.getRenderer();
|
||||
const theme: ThemeInfo = {
|
||||
fg: this.stateService.currentState.theme.fg || this.stateService.currentState.theme.light.fg,
|
||||
bg: this.stateService.currentState.theme.bg || this.stateService.currentState.theme.light.bg
|
||||
};
|
||||
|
||||
if (renderer && renderer.heads && renderer.feet) {
|
||||
this.viewManager.updateHeadersAndFooters(this.currentChapterName || '', this.currentPageInfo, theme);
|
||||
} else {
|
||||
this.viewManager.updateHeadersAndFooters(this.currentChapterName || '', this.currentPageInfo, theme);
|
||||
}
|
||||
}
|
||||
|
||||
if (cfi) {
|
||||
this.currentCfi = cfi;
|
||||
this.updateIsCurrentCfiBookmarked();
|
||||
this.bookmarkService.updateCurrentPosition(cfi, chapterLabel);
|
||||
}
|
||||
}
|
||||
|
||||
private updateIsCurrentCfiBookmarked(): void {
|
||||
if (!this.currentCfi || !this.bookmarks?.length) {
|
||||
this.isCurrentCfiBookmarked = false;
|
||||
return;
|
||||
}
|
||||
this.isCurrentCfiBookmarked = this.bookmarks.some(b => b.cfi === this.currentCfi);
|
||||
}
|
||||
|
||||
private applyStyles(): void {
|
||||
const renderer = this.viewManager.getRenderer();
|
||||
if (renderer) {
|
||||
this.styleService.applyStylesToRenderer(renderer, this.stateService.currentState);
|
||||
if (this.stateService.currentState.flow) {
|
||||
renderer.setAttribute?.('flow', this.stateService.currentState.flow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private syncSettingsToBackend(): void {
|
||||
const setting: EbookViewerSetting = {
|
||||
lineHeight: this.stateService.currentState.lineHeight,
|
||||
justify: this.stateService.currentState.justify,
|
||||
hyphenate: this.stateService.currentState.hyphenate,
|
||||
maxColumnCount: this.stateService.currentState.maxColumnCount,
|
||||
gap: this.stateService.currentState.gap,
|
||||
fontSize: this.stateService.currentState.fontSize,
|
||||
theme: typeof this.stateService.currentState.theme === 'object' && 'name' in this.stateService.currentState.theme
|
||||
? this.stateService.currentState.theme.name
|
||||
: (this.stateService.currentState.theme as any),
|
||||
maxInlineSize: this.stateService.currentState.maxInlineSize,
|
||||
maxBlockSize: this.stateService.currentState.maxBlockSize,
|
||||
fontFamily: this.stateService.currentState.fontFamily,
|
||||
isDark: this.stateService.currentState.isDark,
|
||||
flow: this.stateService.currentState.flow,
|
||||
};
|
||||
this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
onChapterClick(href: string): void {
|
||||
this.viewManager.goTo(href).pipe(
|
||||
tap(() => this.showChapters = false),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
onBookmarkClick(cfi: string): void {
|
||||
this.viewManager.goTo(cfi).pipe(
|
||||
tap(() => {
|
||||
this.showChapters = false;
|
||||
this.currentCfi = cfi;
|
||||
this.updateIsCurrentCfiBookmarked();
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
onCreateBookmark(): void {
|
||||
this.bookmarkService.createBookmarkAtCurrentPosition(this.bookId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(success => {
|
||||
if (success) {
|
||||
this.loadBookmarks();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onDeleteBookmark(bookmarkId: number): void {
|
||||
this.bookMarkService.deleteBookmark(bookmarkId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe({
|
||||
next: () => this.loadBookmarks(),
|
||||
error: () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onProgressChange(fraction: number): void {
|
||||
this.viewManager.goToFraction(fraction)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
onToggleDarkMode(): void {
|
||||
this.stateService.toggleDarkMode();
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
onIncreaseFontSize(): void {
|
||||
this.stateService.updateFontSize(1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
onDecreaseFontSize(): void {
|
||||
this.stateService.updateFontSize(-1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
onIncreaseLineHeight(): void {
|
||||
this.stateService.updateLineHeight(0.1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
onDecreaseLineHeight(): void {
|
||||
this.stateService.updateLineHeight(-0.1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
onSetFlow(flow: 'paginated' | 'scrolled'): void {
|
||||
this.stateService.setFlow(flow);
|
||||
this.syncSettingsToBackend();
|
||||
|
||||
if (flow === 'paginated' && this.currentChapterName) {
|
||||
setTimeout(() => {
|
||||
const renderer = this.viewManager.getRenderer();
|
||||
if (renderer && renderer.heads && renderer.feet) {
|
||||
const theme: ThemeInfo = {
|
||||
fg: this.stateService.currentState.theme.fg || this.stateService.currentState.theme.light.fg,
|
||||
bg: this.stateService.currentState.theme.bg || this.stateService.currentState.theme.light.bg
|
||||
};
|
||||
this.viewManager.updateHeadersAndFooters(this.currentChapterName || '', this.currentPageInfo, theme);
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
|
||||
private toggleHeaderNavbarPinned(): void {
|
||||
this.visibilityManager.togglePinned();
|
||||
}
|
||||
|
||||
@HostListener('document:mousemove', ['$event'])
|
||||
onMouseMove(event: MouseEvent): void {
|
||||
this.visibilityManager.handleMouseMove(event.clientY);
|
||||
}
|
||||
|
||||
@HostListener('document:mouseleave', ['$event'])
|
||||
onMouseLeave(event: MouseEvent): void {
|
||||
this.visibilityManager.handleMouseLeave();
|
||||
}
|
||||
|
||||
@HostListener('window:resize', ['$event'])
|
||||
onWindowResize(event: Event): void {
|
||||
this.visibilityManager.updateWindowHeight(window.innerHeight);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<div
|
||||
class="reader-header"
|
||||
[style.color]="currentTheme?.fg ?? ''"
|
||||
[style.background]="currentTheme?.bg ?? ''"
|
||||
[class.visible]="headerVisible">
|
||||
<button class="icon-btn" (click)="showChapters.emit()" title="Chapters">
|
||||
<i class="pi pi-bars" aria-label="Chapters"></i>
|
||||
</button>
|
||||
<button class="icon-btn" (click)="createBookmark.emit()" title="Create Bookmark">
|
||||
<i class="pi pi-bookmark" aria-label="Create Bookmark"></i>
|
||||
</button>
|
||||
<span class="chapter-title">{{ bookTitle || '' }}</span>
|
||||
<button class="icon-btn" (click)="showControls.emit()" title="Settings">
|
||||
<i class="pi pi-cog" aria-label="Settings"></i>
|
||||
</button>
|
||||
<button class="icon-btn" (click)="close.emit(); $event.stopPropagation()" title="Close Reader">
|
||||
<i class="pi pi-times" aria-label="Close Reader"></i>
|
||||
</button>
|
||||
</div>
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
.reader-header {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 36px;
|
||||
padding: 0 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 14px;
|
||||
z-index: 1000;
|
||||
background: inherit;
|
||||
border-bottom: 1px solid rgba(0,0,0,0.13);
|
||||
box-shadow: 0 2px 8px 0 rgba(0,0,0,0.13);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transform: translateY(-100%);
|
||||
transition: opacity 0.25s ease-out, transform 0.25s ease-out;
|
||||
|
||||
&.visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
padding: 6px;
|
||||
border-radius: 50%;
|
||||
transition: background 0.15s, box-shadow 0.15s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-right: 8px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
box-shadow: 0 2px 8px 0 rgba(0,0,0,0.10);
|
||||
}
|
||||
|
||||
&:last-of-type {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.chapter-title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: inherit;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
min-height: 1.2em;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.reader-header {
|
||||
padding: 0 6px;
|
||||
|
||||
.icon-btn {
|
||||
padding: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import {Component, EventEmitter, Input, Output} from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-reader-header',
|
||||
standalone: true,
|
||||
templateUrl: './reader-header.component.html',
|
||||
styleUrls: ['./reader-header.component.scss']
|
||||
})
|
||||
export class ReaderHeaderComponent {
|
||||
@Input() bookTitle: string | null = null;
|
||||
@Input() currentTheme: any = null;
|
||||
@Input() isDark = false;
|
||||
@Input() fontSize = 16;
|
||||
@Input() lineHeight = 1.5;
|
||||
@Input() forceVisible = false;
|
||||
@Input() flow: 'paginated' | 'scrolled' = 'paginated';
|
||||
@Output() showChapters = new EventEmitter<void>();
|
||||
@Output() showControls = new EventEmitter<void>();
|
||||
@Output() showMetadata = new EventEmitter<void>();
|
||||
@Output() createBookmark = new EventEmitter<void>();
|
||||
@Output() close = new EventEmitter<void>();
|
||||
@Output() toggleDarkMode = new EventEmitter<void>();
|
||||
@Output() increaseFontSize = new EventEmitter<void>();
|
||||
@Output() decreaseFontSize = new EventEmitter<void>();
|
||||
@Output() increaseLineHeight = new EventEmitter<void>();
|
||||
@Output() decreaseLineHeight = new EventEmitter<void>();
|
||||
@Output() setFlow = new EventEmitter<'paginated' | 'scrolled'>();
|
||||
|
||||
get headerVisible(): boolean {
|
||||
return this.forceVisible;
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
<div class="dialog-overlay" (click)="close.emit()">
|
||||
<div class="dialog" (click)="$event.stopPropagation()">
|
||||
<div class="tabs-row">
|
||||
<div class="tabs">
|
||||
<button
|
||||
class="tab"
|
||||
[class.active]="activeTab === 'theme'"
|
||||
(click)="activeTab = 'theme'">
|
||||
Theme
|
||||
</button>
|
||||
<button
|
||||
class="tab"
|
||||
[class.active]="activeTab === 'typography'"
|
||||
(click)="activeTab = 'typography'">
|
||||
Typography
|
||||
</button>
|
||||
<button
|
||||
class="tab"
|
||||
[class.active]="activeTab === 'layout'"
|
||||
(click)="activeTab = 'layout'">
|
||||
Layout
|
||||
</button>
|
||||
</div>
|
||||
<button class="close-btn" (click)="close.emit()">✕</button>
|
||||
</div>
|
||||
|
||||
<div class="dialog-body">
|
||||
@if (activeTab === 'theme') {
|
||||
<div class="tab-content">
|
||||
<div class="section-header dark-mode-header">
|
||||
Dark Mode
|
||||
<span class="mode-switch-wrapper">
|
||||
<span class="mode-icon sun" [class.active]="!state.isDark">☀️</span>
|
||||
<button class="switch" [class.active]="state.isDark" (click)="toggleDarkMode()">
|
||||
<span class="slider"></span>
|
||||
</button>
|
||||
<span class="mode-icon moon" [class.active]="state.isDark">🌙</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="section-header">Theme Colors</div>
|
||||
<div class="theme-grid">
|
||||
@for (theme of themes; track theme.name) {
|
||||
<label class="theme-option">
|
||||
<input
|
||||
type="radio"
|
||||
name="theme"
|
||||
[value]="theme.name"
|
||||
[checked]="state.theme.name === theme.name"
|
||||
(change)="onThemeChange(theme.name)">
|
||||
<div class="theme-card">
|
||||
<div class="theme-colors">
|
||||
<span class="color-swatch" [style.background-color]="state.isDark ? theme.dark.bg : theme.light.bg"></span>
|
||||
<span class="color-swatch" [style.background-color]="state.isDark ? theme.dark.fg : theme.light.fg"></span>
|
||||
</div>
|
||||
<span class="theme-name">{{ theme.label }}</span>
|
||||
</div>
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (activeTab === 'typography') {
|
||||
<div class="tab-content">
|
||||
|
||||
<div class="section-header">Font Settings</div>
|
||||
<div class="control">
|
||||
<label>Font Size</label>
|
||||
<div class="control-right">
|
||||
<div class="stepper">
|
||||
<button (click)="decreaseFontSize()">−</button>
|
||||
<span>{{ state.fontSize }}</span>
|
||||
<button (click)="increaseFontSize()">+</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control">
|
||||
<label>Line Height</label>
|
||||
<div class="control-right">
|
||||
<div class="stepper">
|
||||
<button (click)="decreaseLineHeight()">−</button>
|
||||
<span>{{ state.lineHeight | number:'1.1-1' }}</span>
|
||||
<button (click)="increaseLineHeight()">+</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-header">Font Family</div>
|
||||
<div class="font-grid">
|
||||
@for (font of fonts; track font.value) {
|
||||
<button
|
||||
class="font-option"
|
||||
[class.active]="state.fontFamily === font.value"
|
||||
[style.font-family]="font.value ? getFontFamilyForPreview(font.value) : 'inherit'"
|
||||
(click)="setFontFamily(font.value)">
|
||||
<span class="font-preview">Aa</span>
|
||||
<span class="font-name">{{ font.name }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (activeTab === 'layout') {
|
||||
<div class="tab-content">
|
||||
<div class="section-header">Layout</div>
|
||||
|
||||
<div class="control">
|
||||
<label>Reading Flow</label>
|
||||
<div class="control-right">
|
||||
<div class="radio-group">
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
name="flow"
|
||||
value="paginated"
|
||||
[checked]="state.flow === 'paginated'"
|
||||
(change)="setFlow('paginated')"
|
||||
/>
|
||||
Paginated
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
name="flow"
|
||||
value="scrolled"
|
||||
[checked]="state.flow === 'scrolled'"
|
||||
(change)="setFlow('scrolled')"
|
||||
/>
|
||||
Scrolled
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control">
|
||||
<label>Max Columns</label>
|
||||
<div class="control-right">
|
||||
<div class="stepper">
|
||||
<button (click)="decreaseMaxColumnCount()">−</button>
|
||||
<span>{{ state.maxColumnCount }}</span>
|
||||
<button (click)="increaseMaxColumnCount()">+</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control">
|
||||
<label>Column Gap</label>
|
||||
<div class="control-right gap-control">
|
||||
<input
|
||||
#gapInput
|
||||
type="range"
|
||||
min="0"
|
||||
max="0.5"
|
||||
step="0.01"
|
||||
[value]="state.gap"
|
||||
(input)="setGap(gapInput.valueAsNumber)"
|
||||
/>
|
||||
<span class="value">{{ (state.gap * 100) | number : '1.0-0' }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control">
|
||||
<label>Max Width</label>
|
||||
<div class="control-right">
|
||||
<div class="stepper">
|
||||
<button (click)="decreaseMaxInlineSize()">−</button>
|
||||
<span>{{ state.maxInlineSize }}</span>
|
||||
<button (click)="increaseMaxInlineSize()">+</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="control">
|
||||
<label>Max Height</label>
|
||||
<div class="control-right">
|
||||
<div class="stepper">
|
||||
<button (click)="decreaseMaxBlockSize()">−</button>
|
||||
<span>{{ state.maxBlockSize }}</span>
|
||||
<button (click)="increaseMaxBlockSize()">+</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-header">Text Options</div>
|
||||
|
||||
<div class="toggle-control">
|
||||
<span>Justify Text</span>
|
||||
<button class="switch" [class.active]="state.justify" (click)="toggleJustify()">
|
||||
<span class="slider"></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="toggle-control">
|
||||
<span>Hyphenate</span>
|
||||
<button class="switch" [class.active]="state.hyphenate" (click)="toggleHyphenate()">
|
||||
<span class="slider"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+672
@@ -0,0 +1,672 @@
|
||||
.dialog-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
z-index: 12000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.dialog {
|
||||
background: rgba(30, 30, 30, 0.95);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 520px;
|
||||
height: 600px;
|
||||
max-height: 85vh;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||
animation: slideUp 0.3s ease-out;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
transform: translateY(20px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-header {
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
}
|
||||
|
||||
.tabs-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
padding: 0 20px;
|
||||
margin-bottom: 18px;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.tabs-row-spacer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tab {
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
padding: 12px 18px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
position: relative;
|
||||
transition: all 0.2s ease;
|
||||
text-align: center;
|
||||
min-width: 80px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: #ffffff;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 0;
|
||||
transform: translateX(-50%);
|
||||
width: 60%;
|
||||
height: 2px;
|
||||
background: #4a9eff;
|
||||
border-radius: 1px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
position: absolute;
|
||||
right: 20px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
margin-left: 0;
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
border-radius: 6px;
|
||||
transition: all 0.2s ease;
|
||||
line-height: 1;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-body {
|
||||
padding: 20px 25px;
|
||||
overflow-y: auto;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
max-height: 100%;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-radius: 4px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
section {
|
||||
margin-bottom: 20px;
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
border-bottom: none;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 0 0 10px 0;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
.mode-toggle,
|
||||
.toggle-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 0;
|
||||
margin-bottom: 2px;
|
||||
|
||||
span {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
.mode-switch-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.mode-icon {
|
||||
font-size: 18px;
|
||||
opacity: 0.3;
|
||||
transition: all 0.3s ease;
|
||||
user-select: none;
|
||||
|
||||
&.active {
|
||||
opacity: 1;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
&.sun {
|
||||
filter: grayscale(100%);
|
||||
|
||||
&.active {
|
||||
filter: grayscale(0%);
|
||||
}
|
||||
}
|
||||
|
||||
&.moon {
|
||||
filter: grayscale(100%);
|
||||
|
||||
&.active {
|
||||
filter: grayscale(0%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.switch {
|
||||
position: relative;
|
||||
width: 44px;
|
||||
height: 24px;
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
transition: background 0.3s ease;
|
||||
padding: 0;
|
||||
|
||||
&.active {
|
||||
background: #4a9eff;
|
||||
|
||||
.slider {
|
||||
transform: translateX(20px);
|
||||
}
|
||||
}
|
||||
|
||||
.slider {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
background: #ffffff;
|
||||
border-radius: 50%;
|
||||
transition: transform 0.3s ease;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
|
||||
&.active {
|
||||
background: #5ba9ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.theme-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 14px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.theme-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.theme-option {
|
||||
cursor: pointer;
|
||||
|
||||
input[type="radio"] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.theme-card {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 2px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
transition: all 0.2s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
input:checked + .theme-card {
|
||||
border-color: #4a9eff;
|
||||
background: rgba(74, 158, 255, 0.1);
|
||||
}
|
||||
|
||||
.theme-colors {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
.color-swatch {
|
||||
flex: 1;
|
||||
border-radius: 3px;
|
||||
border: 1px solid rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.theme-name {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.font-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 14px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.font-option {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 2px solid rgba(255, 255, 255, 0.1);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
&.active {
|
||||
border-color: #4a9eff;
|
||||
background: rgba(74, 158, 255, 0.1);
|
||||
}
|
||||
|
||||
.font-preview {
|
||||
font-size: 24px;
|
||||
color: #ffffff;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.font-name {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
.control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 16px;
|
||||
min-height: 32px;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
> label {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
&.checkbox-control {
|
||||
label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
padding: 4px 0;
|
||||
transition: color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
accent-color: #4a9eff;
|
||||
}
|
||||
|
||||
span {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
input[type="range"] {
|
||||
flex: 1;
|
||||
margin: 0 10px;
|
||||
height: 5px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
border-radius: 3px;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
|
||||
&::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
background: #4a9eff;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
box-shadow: 0 2px 8px rgba(74, 158, 255, 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
&::-moz-range-thumb {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
background: #4a9eff;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
box-shadow: 0 2px 8px rgba(74, 158, 255, 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.value {
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
font-size: 12px;
|
||||
min-width: 42px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
select {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #ffffff;
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
min-width: 130px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
border-color: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
border-color: #4a9eff;
|
||||
box-shadow: 0 0 0 3px rgba(74, 158, 255, 0.1);
|
||||
}
|
||||
|
||||
option {
|
||||
background: #1e1e1e;
|
||||
color: #ffffff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.control-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.gap-control {
|
||||
flex: 1;
|
||||
max-width: 200px;
|
||||
min-width: 160px;
|
||||
|
||||
input[type="range"] {
|
||||
flex: 1;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.value {
|
||||
min-width: 38px;
|
||||
}
|
||||
}
|
||||
|
||||
.stepper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
padding: 3px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
|
||||
button {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s ease;
|
||||
font-weight: 300;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
}
|
||||
|
||||
span {
|
||||
min-width: 48px;
|
||||
text-align: center;
|
||||
color: #ffffff;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
}
|
||||
|
||||
.toggle {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
.icon {
|
||||
display: block;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
border-color: rgba(255, 255, 255, 0.25);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.section-header {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
margin-top: 24px;
|
||||
margin-bottom: 12px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
|
||||
&:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
&.dark-mode-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
gap: 30px;
|
||||
padding-bottom: 8px;
|
||||
margin-bottom: 30px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.radio-group {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
|
||||
label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
font-weight: 500;
|
||||
position: relative;
|
||||
user-select: none;
|
||||
|
||||
input[type="radio"] {
|
||||
appearance: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 2px solid #4a9eff;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
margin: 0 6px 0 0;
|
||||
outline: none;
|
||||
transition: border-color 0.2s, box-shadow 0.2s;
|
||||
|
||||
&:checked {
|
||||
background: #4a9eff;
|
||||
box-shadow: 0 0 0 2px rgba(74, 158, 255, 0.15);
|
||||
border-color: #4a9eff;
|
||||
}
|
||||
|
||||
&:focus {
|
||||
box-shadow: 0 0 0 2px #4a9eff;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import {Component, EventEmitter, Inject, Input, OnInit, Output, Renderer2} from '@angular/core';
|
||||
import {DecimalPipe, DOCUMENT} from '@angular/common';
|
||||
import {ReaderStateService} from '../../services/reader-state.service';
|
||||
import {ReaderViewManagerService} from '../../services/reader-view-manager.service';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
import {EpubCustomFontService} from '../../../epub-reader/service/epub-custom-font.service';
|
||||
import {EbookViewerSetting} from '../../../../book/model/book.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-settings-dialog',
|
||||
standalone: true,
|
||||
imports: [DecimalPipe],
|
||||
templateUrl: './reader-settings-dialog.component.html',
|
||||
styleUrls: ['./reader-settings-dialog.component.scss']
|
||||
})
|
||||
export class ReaderSettingsDialogComponent implements OnInit {
|
||||
@Input() stateService!: ReaderStateService;
|
||||
@Input() viewManager!: ReaderViewManagerService;
|
||||
@Input() bookId!: number;
|
||||
|
||||
@Output() close = new EventEmitter<void>();
|
||||
|
||||
activeTab: 'theme' | 'typography' | 'layout' = 'theme';
|
||||
|
||||
constructor(
|
||||
private bookService: BookService,
|
||||
private customFontService: EpubCustomFontService,
|
||||
private renderer: Renderer2,
|
||||
@Inject(DOCUMENT) private document: Document
|
||||
) {
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.customFontService.injectCustomFontsStylesheet(this.renderer, this.document);
|
||||
}
|
||||
|
||||
getFontFamilyForPreview(fontValue: string): string {
|
||||
return this.customFontService.getFontFamilyForPreview(fontValue);
|
||||
}
|
||||
|
||||
get state() {
|
||||
return this.stateService.currentState;
|
||||
}
|
||||
|
||||
get themes() {
|
||||
return this.stateService.themes;
|
||||
}
|
||||
|
||||
get fonts() {
|
||||
return this.stateService.fonts;
|
||||
}
|
||||
|
||||
private syncSettingsToBackend() {
|
||||
const setting: EbookViewerSetting = {
|
||||
lineHeight: this.state.lineHeight,
|
||||
justify: this.state.justify,
|
||||
hyphenate: this.state.hyphenate,
|
||||
maxColumnCount: this.state.maxColumnCount,
|
||||
gap: this.state.gap,
|
||||
fontSize: this.state.fontSize,
|
||||
theme: typeof this.state.theme === 'object' && 'name' in this.state.theme ? this.state.theme.name : (this.state.theme as any),
|
||||
maxInlineSize: this.state.maxInlineSize,
|
||||
maxBlockSize: this.state.maxBlockSize,
|
||||
fontFamily: this.state.fontFamily,
|
||||
isDark: this.state.isDark,
|
||||
flow: this.state.flow,
|
||||
};
|
||||
this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId).subscribe();
|
||||
}
|
||||
|
||||
setFontFamily(value: string | null) {
|
||||
this.stateService.setFontFamily(value);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
increaseFontSize() {
|
||||
this.stateService.updateFontSize(1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
decreaseFontSize() {
|
||||
this.stateService.updateFontSize(-1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
increaseLineHeight() {
|
||||
this.stateService.updateLineHeight(0.1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
decreaseLineHeight() {
|
||||
this.stateService.updateLineHeight(-0.1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
increaseMaxColumnCount() {
|
||||
this.stateService.updateMaxColumnCount(1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
decreaseMaxColumnCount() {
|
||||
this.stateService.updateMaxColumnCount(-1);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
setGap(value: number) {
|
||||
const delta = value - this.state.gap;
|
||||
this.stateService.updateGap(delta);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
toggleJustify() {
|
||||
this.stateService.toggleJustify();
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
toggleHyphenate() {
|
||||
this.stateService.toggleHyphenate();
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
increaseMaxInlineSize() {
|
||||
this.stateService.updateMaxInlineSize(40);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
decreaseMaxInlineSize() {
|
||||
this.stateService.updateMaxInlineSize(-40);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
increaseMaxBlockSize() {
|
||||
this.stateService.updateMaxBlockSize(60);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
decreaseMaxBlockSize() {
|
||||
this.stateService.updateMaxBlockSize(-60);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
toggleDarkMode() {
|
||||
this.stateService.toggleDarkMode();
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
onThemeChange(themeName: string) {
|
||||
this.stateService.setThemeByName(themeName);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
|
||||
setFlow(flow: 'paginated' | 'scrolled') {
|
||||
this.stateService.setFlow(flow);
|
||||
this.viewManager.getRenderer()?.setAttribute?.('flow', flow);
|
||||
this.syncSettingsToBackend();
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
<div
|
||||
class="reader-navbar"
|
||||
[style.color]="'#ffffff'"
|
||||
[style.background]="'#1a1a1a'"
|
||||
[class.visible]="navbarVisible">
|
||||
|
||||
<button class="icon-btn" title="Previous">
|
||||
<i class="pi pi-caret-left" aria-label="Previous"></i>
|
||||
</button>
|
||||
|
||||
<div class="progress-section">
|
||||
<button class="location-btn" (click)="toggleLocationPopover()" title="Location">
|
||||
<span class="location-text">{{ currentPercentage }}%</span>
|
||||
</button>
|
||||
|
||||
<div class="progress-slider-wrapper">
|
||||
<input
|
||||
type="range"
|
||||
class="progress-slider"
|
||||
[min]="0"
|
||||
[max]="100"
|
||||
[value]="currentPercentage"
|
||||
(input)="onProgressChange($event)"
|
||||
title="Progress"/>
|
||||
<div class="progress-ticks">
|
||||
@for (frac of sectionFractions; track frac) {
|
||||
<span class="progress-tick" [style.left.%]="frac * 100"></span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="icon-btn" title="Next">
|
||||
<i class="pi pi-caret-right" aria-label="Next"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (showLocationPopover) {
|
||||
<div class="location-popover" [style.color]="'#ffffff'" [style.background]="'#1a1a1a'" (mousedown)="$event.preventDefault()">
|
||||
<div class="popover-content">
|
||||
<div class="time-info">
|
||||
<div class="time-section">
|
||||
<span class="label">Time Left in Section</span>
|
||||
<span class="value">{{ timeSection }}</span>
|
||||
</div>
|
||||
<div class="separator"></div>
|
||||
<div class="time-section">
|
||||
<span class="label">Time Left in Book</span>
|
||||
<span class="value">{{ timeTotal }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="location-controls">
|
||||
<div class="control-row">
|
||||
<label>Page</label>
|
||||
<span>{{ currentPage }}</span>
|
||||
</div>
|
||||
<div class="control-row">
|
||||
<label>Location</label>
|
||||
<input type="number" [value]="locationCurrent"/>
|
||||
<span>/ {{ locationTotal }}</span>
|
||||
</div>
|
||||
<div class="control-row">
|
||||
<label>Section</label>
|
||||
<span>{{ sectionCurrent }} / {{ sectionTotal }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="section-navigation">
|
||||
<button class="nav-btn" title="First Section" (click)="onFirstSection()">
|
||||
<i class="pi pi-step-backward"></i>
|
||||
</button>
|
||||
<button class="nav-btn" title="Previous Section" (click)="onPreviousSection()">
|
||||
<i class="pi pi-caret-left"></i>
|
||||
</button>
|
||||
<button class="nav-btn" title="Jump To…">
|
||||
<i class="pi pi-ellipsis-v"></i>
|
||||
</button>
|
||||
<button class="nav-btn" title="Next Section" (click)="onNextSection()">
|
||||
<i class="pi pi-caret-right"></i>
|
||||
</button>
|
||||
<button class="nav-btn" title="Last Section" (click)="onLastSection()">
|
||||
<i class="pi pi-step-forward"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
.reader-navbar {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 40px;
|
||||
padding: 0 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
z-index: 1000;
|
||||
background: rgba(30, 30, 30, 0.95);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
box-shadow: 0 -2px 8px 0 rgba(0, 0, 0, 0.3);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transform: translateY(100%);
|
||||
transition: opacity 0.25s ease-out, transform 0.25s ease-out;
|
||||
color: white;
|
||||
|
||||
&.visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
border-radius: 50%;
|
||||
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
aspect-ratio: 1 / 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.10);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.progress-section {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
|
||||
.location-btn {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
padding: 4px 12px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: #ffffff;
|
||||
}
|
||||
}
|
||||
|
||||
.progress-slider-wrapper {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
.progress-slider {
|
||||
flex: 1;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
outline: none;
|
||||
-webkit-appearance: none;
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
|
||||
&::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: #4a9eff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&::-moz-range-thumb {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: #4a9eff;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
.progress-ticks {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 50%;
|
||||
width: 100%;
|
||||
height: 10px;
|
||||
transform: translateY(-50%);
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.progress-tick {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
width: 1.5px;
|
||||
height: 10px;
|
||||
background: rgba(255, 255, 255, 0.5);
|
||||
border-radius: 2px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.location-popover {
|
||||
position: absolute;
|
||||
bottom: 58px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: rgba(30, 30, 30, 0.95);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
|
||||
z-index: 1001;
|
||||
min-width: 380px;
|
||||
animation: popoverSlideIn 0.15s ease-out;
|
||||
transform-origin: bottom center;
|
||||
color: white;
|
||||
|
||||
.popover-content {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.time-info {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
align-items: center;
|
||||
justify-content: space-around;
|
||||
padding: 8px 0;
|
||||
|
||||
.time-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
text-align: center;
|
||||
flex: 1;
|
||||
|
||||
.label {
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.value {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.3px;
|
||||
color: #ffffff;
|
||||
}
|
||||
}
|
||||
|
||||
.separator {
|
||||
width: 1px;
|
||||
height: 44px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
}
|
||||
|
||||
.divider {
|
||||
height: 1px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.location-controls {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 4px 0;
|
||||
|
||||
.control-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
|
||||
label {
|
||||
min-width: 70px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
|
||||
input {
|
||||
width: 65px;
|
||||
padding: 6px 10px;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 6px;
|
||||
color: #ffffff;
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
transition: background 0.15s, border-color 0.15s;
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: 13px;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.section-navigation {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
.nav-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease, color 0.15s ease;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
min-width: 40px;
|
||||
min-height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.15);
|
||||
transform: scale(1.05);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
&:active {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
transform: scale(0.95);
|
||||
}
|
||||
|
||||
i {
|
||||
font-size: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes popoverSlideIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(-50%) translateY(4px) scale(0.95);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(-50%) translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
import {Component, EventEmitter, HostListener, inject, Input, Output} from '@angular/core';
|
||||
import {ReaderViewManagerService} from '../../services/reader-view-manager.service';
|
||||
|
||||
interface TocItem {
|
||||
label: string;
|
||||
href: string;
|
||||
subitems: any;
|
||||
id: number;
|
||||
}
|
||||
|
||||
interface PageItem {
|
||||
label: string;
|
||||
href: string;
|
||||
subitems: any;
|
||||
id: number;
|
||||
}
|
||||
|
||||
interface RelocateEventDetail {
|
||||
fraction: number;
|
||||
section: { current: number; total: number };
|
||||
location: { current: number; next: number; total: number };
|
||||
time: { section: number; total: number };
|
||||
tocItem: TocItem;
|
||||
pageItem: PageItem;
|
||||
cfi: string;
|
||||
range: any;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-reader-navbar',
|
||||
standalone: true,
|
||||
templateUrl: './reader-navbar.component.html',
|
||||
styleUrls: ['./reader-navbar.component.scss']
|
||||
})
|
||||
export class ReaderNavbarComponent {
|
||||
@Input() progressData: RelocateEventDetail | null = null;
|
||||
@Input() forceVisible = false;
|
||||
@Input() sectionFractions: number[] = [];
|
||||
@Output() progressChange = new EventEmitter<number>();
|
||||
|
||||
private managerService = inject(ReaderViewManagerService);
|
||||
showLocationPopover = false;
|
||||
|
||||
@HostListener('document:click', ['$event'])
|
||||
onDocumentClick(event: MouseEvent) {
|
||||
const target = event.target as HTMLElement;
|
||||
const clickedInside = target.closest('.location-popover') || target.closest('.location-btn');
|
||||
if (!clickedInside && this.showLocationPopover) {
|
||||
this.showLocationPopover = false;
|
||||
}
|
||||
}
|
||||
|
||||
@HostListener('window:blur')
|
||||
onWindowBlur() {
|
||||
setTimeout(() => {
|
||||
if (this.showLocationPopover) {
|
||||
this.showLocationPopover = false;
|
||||
}
|
||||
}, 200);
|
||||
}
|
||||
|
||||
toggleLocationPopover() {
|
||||
this.showLocationPopover = !this.showLocationPopover;
|
||||
}
|
||||
|
||||
get currentFraction(): number {
|
||||
return this.progressData?.fraction ?? 0;
|
||||
}
|
||||
|
||||
get currentPercentage(): number {
|
||||
return Math.round(this.currentFraction * 100);
|
||||
}
|
||||
|
||||
get timeTotal(): string {
|
||||
return this.formatDuration((this.progressData?.time.total ?? 0) * 60);
|
||||
}
|
||||
|
||||
get timeSection(): string {
|
||||
return this.formatDuration((this.progressData?.time.section ?? 0) * 60);
|
||||
}
|
||||
|
||||
get locationCurrent(): number {
|
||||
return this.progressData?.location.current ?? 0;
|
||||
}
|
||||
|
||||
get locationTotal(): number {
|
||||
return this.progressData?.location.total ?? 0;
|
||||
}
|
||||
|
||||
get sectionCurrent(): number {
|
||||
return this.progressData?.section.current ?? 0;
|
||||
}
|
||||
|
||||
get sectionTotal(): number {
|
||||
return this.progressData?.section.total ?? 0;
|
||||
}
|
||||
|
||||
get currentPage(): string {
|
||||
return this.progressData?.pageItem?.label ?? 'N/A';
|
||||
}
|
||||
|
||||
get navbarVisible(): boolean {
|
||||
return this.forceVisible;
|
||||
}
|
||||
|
||||
onProgressChange(event: Event) {
|
||||
const target = event.target as HTMLInputElement;
|
||||
const fraction = parseFloat(target.value) / 100;
|
||||
this.progressChange.emit(fraction);
|
||||
}
|
||||
|
||||
onFirstSection() {
|
||||
this.managerService.goToSection(0).subscribe();
|
||||
}
|
||||
|
||||
onPreviousSection(): void {
|
||||
const s = this.progressData?.section;
|
||||
if (!s || s.current <= 0) return;
|
||||
this.managerService.goToSection(s.current - 1).subscribe();
|
||||
}
|
||||
|
||||
onNextSection(): void {
|
||||
const s = this.progressData?.section;
|
||||
if (!s || s.current >= s.total - 1) return;
|
||||
this.managerService.goToSection(s.current + 1).subscribe();
|
||||
}
|
||||
|
||||
onLastSection(): void {
|
||||
const s = this.progressData?.section;
|
||||
if (!s || s.total <= 0) return;
|
||||
this.managerService.goToSection(s.total - 1).subscribe();
|
||||
}
|
||||
|
||||
private formatDuration(seconds: number): string {
|
||||
if (seconds < 60) return `${Math.round(seconds)} sec`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return `${minutes} min`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remainingMinutes = minutes % 60;
|
||||
return remainingMinutes > 0
|
||||
? `${hours} hr ${remainingMinutes} min`
|
||||
: `${hours} hr`;
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<div class="dialog-overlay" (click)="close.emit()">
|
||||
<div class="dialog" (click)="$event.stopPropagation()">
|
||||
<div class="dialog-header">
|
||||
<h2>Book Information</h2>
|
||||
<button class="close-btn" (click)="close.emit()">✕</button>
|
||||
</div>
|
||||
|
||||
<div class="dialog-body">
|
||||
<div class="metadata-container">
|
||||
<div class="cover-section">
|
||||
@if (bookCoverUrl) {
|
||||
<img [src]="bookCoverUrl" [alt]="metadata?.title || 'Book cover'" class="book-cover">
|
||||
} @else {
|
||||
<div class="cover-placeholder">
|
||||
<span class="placeholder-icon">📚</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="metadata-section">
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">Basic Information</h3>
|
||||
|
||||
<div class="metadata-item">
|
||||
<span class="label">Title</span>
|
||||
<span class="value">{{ metadata?.title || 'Unknown' }}</span>
|
||||
</div>
|
||||
|
||||
@if (metadata?.subtitle) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Subtitle</span>
|
||||
<span class="value">{{ metadata?.subtitle }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="metadata-item">
|
||||
<span class="label">Author(s)</span>
|
||||
<span class="value">{{ formatAuthors(metadata?.authors) }}</span>
|
||||
</div>
|
||||
|
||||
@if (metadata?.publisher) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Publisher</span>
|
||||
<span class="value">{{ metadata?.publisher }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.publishedDate) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Published</span>
|
||||
<span class="value">{{ formatDate(metadata?.publishedDate) }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.language) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Language</span>
|
||||
<span class="value">{{ metadata?.language }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.pageCount) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Pages</span>
|
||||
<span class="value">{{ metadata?.pageCount }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (metadata?.seriesName) {
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">Series</h3>
|
||||
|
||||
<div class="metadata-item">
|
||||
<span class="label">Series Name</span>
|
||||
<span class="value">{{ metadata?.seriesName }}</span>
|
||||
</div>
|
||||
|
||||
@if (metadata?.seriesNumber) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Book Number</span>
|
||||
<span class="value">
|
||||
{{ metadata?.seriesNumber }}@if (metadata?.seriesTotal) {
|
||||
/ {{ metadata?.seriesTotal }}
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.isbn13 || metadata?.isbn10 || metadata?.asin) {
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">Identifiers</h3>
|
||||
|
||||
@if (metadata?.isbn13) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">ISBN-13</span>
|
||||
<span class="value">{{ metadata?.isbn13 }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.isbn10) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">ISBN-10</span>
|
||||
<span class="value">{{ metadata?.isbn10 }}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.asin) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">ASIN</span>
|
||||
<span class="value">{{ metadata?.asin }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.rating || metadata?.goodreadsRating || metadata?.amazonRating) {
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">Ratings</h3>
|
||||
|
||||
@if (metadata?.goodreadsRating) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Goodreads</span>
|
||||
<span class="value">
|
||||
⭐ {{ metadata?.goodreadsRating?.toFixed(2) }}
|
||||
@if (metadata?.goodreadsReviewCount) {
|
||||
<span class="review-count">({{ metadata?.goodreadsReviewCount }} reviews)</span>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.amazonRating) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">Amazon</span>
|
||||
<span class="value">
|
||||
⭐ {{ metadata?.amazonRating?.toFixed(2) }}
|
||||
@if (metadata?.amazonReviewCount) {
|
||||
<span class="review-count">({{ metadata?.amazonReviewCount }} reviews)</span>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.categories && metadata?.categories!.length > 0) {
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">Categories</h3>
|
||||
<div class="tags-container">
|
||||
@for (category of metadata?.categories; track category) {
|
||||
<span class="tag">{{ category }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.tags && metadata?.tags!.length > 0) {
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">Tags</h3>
|
||||
<div class="tags-container">
|
||||
@for (tag of metadata?.tags; track tag) {
|
||||
<span class="tag">{{ tag }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (book?.fileSizeKb) {
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">File Information</h3>
|
||||
|
||||
<div class="metadata-item">
|
||||
<span class="label">File Size</span>
|
||||
<span class="value">{{ formatFileSize(book?.fileSizeKb) }}</span>
|
||||
</div>
|
||||
|
||||
@if (book?.fileName) {
|
||||
<div class="metadata-item">
|
||||
<span class="label">File Name</span>
|
||||
<span class="value file-name">{{ book?.fileName }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (metadata?.description) {
|
||||
<div class="metadata-group">
|
||||
<h3 class="section-title">Description</h3>
|
||||
<p class="description">{{ metadata?.description }}</p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
.dialog-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
z-index: 12000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.dialog {
|
||||
background: rgba(30, 30, 30, 0.95);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
border-radius: 12px;
|
||||
width: 90%;
|
||||
max-width: 800px;
|
||||
max-height: 85vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||
animation: slideUp 0.3s ease-out;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: 95%;
|
||||
max-height: 90vh;
|
||||
margin: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
transform: translateY(20px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-header {
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
transition: all 0.2s ease;
|
||||
line-height: 1;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-body {
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-radius: 4px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.metadata-container {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.cover-section {
|
||||
flex-shrink: 0;
|
||||
width: 240px;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: 100%;
|
||||
max-width: 180px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
|
||||
max-height: 360px;
|
||||
object-fit: cover;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-height: 270px;
|
||||
}
|
||||
}
|
||||
|
||||
.cover-placeholder {
|
||||
width: 100%;
|
||||
aspect-ratio: 2/3;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, 0.05) 0%, rgba(255, 255, 255, 0.02) 100%);
|
||||
border: 2px dashed rgba(255, 255, 255, 0.15);
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-height: 270px;
|
||||
}
|
||||
|
||||
.placeholder-icon {
|
||||
font-size: 64px;
|
||||
opacity: 0.3;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
font-size: 48px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.metadata-section {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.metadata-group {
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
|
||||
&:not(:last-child) {
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
}
|
||||
|
||||
.section-title {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
margin: 0 0 12px 0;
|
||||
}
|
||||
|
||||
.metadata-item {
|
||||
display: grid;
|
||||
grid-template-columns: 120px 1fr;
|
||||
gap: 12px;
|
||||
margin-bottom: 10px;
|
||||
align-items: start;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.label {
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.value {
|
||||
color: rgba(255, 255, 255, 0.95);
|
||||
font-size: 13px;
|
||||
word-break: break-word;
|
||||
|
||||
&.file-name {
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 12px;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
}
|
||||
|
||||
.review-count {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 12px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.tags-container {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.tag {
|
||||
background: rgba(74, 158, 255, 0.15);
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
border: 1px solid rgba(74, 158, 255, 0.25);
|
||||
}
|
||||
|
||||
.description {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import {Component, EventEmitter, inject, Input, Output} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {Book} from '../../../../book/model/book.model';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-reader-book-metadata-dialog',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
templateUrl: './reader-book-metadata-dialog.component.html',
|
||||
styleUrls: ['./reader-book-metadata-dialog.component.scss']
|
||||
})
|
||||
export class ReaderBookMetadataDialogComponent {
|
||||
@Input() book: Book | null = null;
|
||||
@Output() close = new EventEmitter<void>();
|
||||
|
||||
private urlHelperService = inject(UrlHelperService);
|
||||
|
||||
get metadata() {
|
||||
return this.book?.metadata;
|
||||
}
|
||||
|
||||
get bookCoverUrl(): string | null {
|
||||
if (!this.book?.id) return null;
|
||||
const coverUpdatedOn = this.book.metadata?.coverUpdatedOn;
|
||||
return this.urlHelperService.getCoverUrl(this.book.id, coverUpdatedOn);
|
||||
}
|
||||
|
||||
formatDate(date: string | undefined): string {
|
||||
if (!date) return 'N/A';
|
||||
try {
|
||||
return new Date(date).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
} catch {
|
||||
return date;
|
||||
}
|
||||
}
|
||||
|
||||
formatAuthors(authors: string[] | undefined): string {
|
||||
if (!authors || authors.length === 0) return 'Unknown';
|
||||
return authors.join(', ');
|
||||
}
|
||||
|
||||
formatFileSize(sizeKb: number | undefined): string {
|
||||
if (!sizeKb) return 'N/A';
|
||||
if (sizeKb < 1024) return `${sizeKb.toFixed(1)} KB`;
|
||||
return `${(sizeKb / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
<div class="dialog-overlay"
|
||||
(click)="onOverlayClick()"
|
||||
[class.closing]="closing">
|
||||
<div class="sidebar"
|
||||
(click)="$event.stopPropagation()"
|
||||
[class.closing]="closing">
|
||||
<div class="sidebar-header">
|
||||
<div class="sidebar-header-book">
|
||||
@if (bookCoverUrl) {
|
||||
<img
|
||||
[src]="bookCoverUrl"
|
||||
alt="Book cover"
|
||||
class="sidebar-book-cover clickable"
|
||||
(click)="onCoverClick()"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
(keydown.enter)="onCoverClick()"
|
||||
(keydown.space)="onCoverClick()"
|
||||
title="View book details"
|
||||
/>
|
||||
}
|
||||
<div class="sidebar-book-meta">
|
||||
<div class="sidebar-book-title ellipsis">{{ bookTitle }}</div>
|
||||
@if (bookAuthors) {
|
||||
<div class="sidebar-book-authors ellipsis">{{ bookAuthors }}</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sidebar-tabs">
|
||||
<button
|
||||
class="tab-btn"
|
||||
[class.active]="activeTab === 'chapters'"
|
||||
(click)="activeTab = 'chapters'"
|
||||
aria-label="Chapters"
|
||||
>
|
||||
<i class="pi pi-book tab-icon"></i>
|
||||
<span class="tab-label">Chapters</span>
|
||||
</button>
|
||||
<button
|
||||
class="tab-btn"
|
||||
[class.active]="activeTab === 'bookmarks'"
|
||||
(click)="activeTab = 'bookmarks'"
|
||||
aria-label="Bookmarks"
|
||||
>
|
||||
<i class="pi pi-bookmark tab-icon"></i>
|
||||
<span class="tab-label">Bookmarks</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="sidebar-body">
|
||||
@switch (activeTab) {
|
||||
@case ('chapters') {
|
||||
<ul class="chapter-list">
|
||||
@for (chapter of chapters; track chapter.href) {
|
||||
<ng-container *ngTemplateOutlet="chapterNode; context: { $implicit: chapter, level: 0 }"></ng-container>
|
||||
}
|
||||
</ul>
|
||||
<ng-template #chapterNode let-chapter let-level="level">
|
||||
<li>
|
||||
<div class="chapter-row"
|
||||
[class.has-subchapters]="chapter.subitems?.length"
|
||||
[class.active]="isChapterActive(chapter.href)"
|
||||
[style.paddingLeft.px]="12 + (level * 16)"
|
||||
(click)="chapter.subitems?.length ? toggleChapterExpand(chapter.href) : onChapterClick(chapter.href)">
|
||||
<span class="chapter-label ellipsis">{{ chapter.label }}</span>
|
||||
@if (chapter.subitems?.length) {
|
||||
<span class="accordion-icon" [class.expanded]="isChapterExpanded(chapter.href)">
|
||||
<i class="pi" [ngClass]="isChapterExpanded(chapter.href) ? 'pi-chevron-down' : 'pi-chevron-right'"></i>
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
@if (chapter.subitems?.length && isChapterExpanded(chapter.href)) {
|
||||
<ul class="subchapter-list">
|
||||
@for (sub of chapter.subitems; track sub.href) {
|
||||
<ng-container *ngTemplateOutlet="chapterNode; context: { $implicit: sub, level: level + 1 }"></ng-container>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</li>
|
||||
</ng-template>
|
||||
}
|
||||
@case ('bookmarks') {
|
||||
@if (bookmarks.length > 0) {
|
||||
<ul>
|
||||
@for (bookmark of bookmarks; track bookmark.id) {
|
||||
<li class="bookmark-item" (click)="onBookmarkClick(bookmark.cfi)">
|
||||
<div class="bookmark-info">
|
||||
<div class="bookmark-title ellipsis">{{ bookmark.title }}</div>
|
||||
<div class="bookmark-date">{{ bookmark.createdAt | date: 'short' }}</div>
|
||||
</div>
|
||||
<button class="bookmark-delete-btn" (click)="onDeleteBookmark($event, bookmark.id)" aria-label="Delete bookmark">
|
||||
×
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
} @else {
|
||||
<div class="empty-tab">No bookmarks yet.</div>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
.dialog-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
z-index: 12000;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
animation: fadeIn 200ms ease-out;
|
||||
|
||||
&.closing {
|
||||
animation: fadeOut 200ms ease-in forwards;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeOut {
|
||||
from {
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
width: 260px;
|
||||
background: rgba(30, 30, 30, 0.95);
|
||||
backdrop-filter: blur(20px);
|
||||
-webkit-backdrop-filter: blur(20px);
|
||||
box-shadow: 8px 0 32px rgba(0, 0, 0, 0.5);
|
||||
z-index: 13001;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
color: white;
|
||||
border-top-right-radius: 12px;
|
||||
border-bottom-right-radius: 12px;
|
||||
overflow: hidden;
|
||||
animation: slideIn 250ms ease-out;
|
||||
|
||||
&.closing {
|
||||
animation: slideOut 250ms ease-in forwards;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideOut {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
}
|
||||
to {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
padding: 16px;
|
||||
min-height: 100px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.sidebar-header-book {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.sidebar-book-cover {
|
||||
width: 84px;
|
||||
height: 117px;
|
||||
object-fit: cover;
|
||||
border-radius: 2px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.13);
|
||||
background: #222;
|
||||
flex-shrink: 0;
|
||||
|
||||
&.clickable {
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s ease, opacity 0.2s ease, box-shadow 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.05);
|
||||
opacity: 0.9;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid #4a90e2;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-book-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
gap: 4px;
|
||||
|
||||
.sidebar-book-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
margin-bottom: 2px;
|
||||
line-height: 1.2;
|
||||
max-width: 220px;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 3;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
word-break: break-word;
|
||||
max-height: calc(1.2em * 3);
|
||||
}
|
||||
|
||||
.sidebar-book-authors {
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
line-height: 1.2;
|
||||
max-width: 220px;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
word-break: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 12px 0 12px 0;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-radius: 4px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
li {
|
||||
padding: 6px 12px 6px 12px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
border-radius: 8px;
|
||||
margin: 1px 8px;
|
||||
transition: background 0.2s ease, color 0.2s ease;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
background: transparent;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
border-bottom: none;
|
||||
|
||||
.chapter-label {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ellipsis {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.bookmark-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
|
||||
.bookmark-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.bookmark-title {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
|
||||
.bookmark-date {
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
.bookmark-delete-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
cursor: pointer;
|
||||
font-size: 18px;
|
||||
padding: 4px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.2s ease, color 0.2s ease;
|
||||
flex-shrink: 0;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #ffffff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-tabs {
|
||||
display: flex;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
height: 50px;
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
z-index: 13002;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.sidebar-tabs > * {
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
position: relative;
|
||||
transition: background 0.15s ease, color 0.15s ease;
|
||||
}
|
||||
|
||||
.sidebar-tabs > *:hover {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.sidebar-tabs > *.active {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.sidebar-tabs > *:not(:last-child)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 8px;
|
||||
bottom: 8px;
|
||||
width: 1px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.tab-btn {
|
||||
flex: 1;
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
font-size: 13px;
|
||||
padding: 8px 0;
|
||||
cursor: pointer;
|
||||
border-radius: 0;
|
||||
transition: all 0.2s ease;
|
||||
outline: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
position: relative;
|
||||
z-index: 13003;
|
||||
|
||||
&.active {
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
background: transparent;
|
||||
border-bottom: 1.5px solid white;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
&:hover:not(.active) {
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
z-index: 2;
|
||||
}
|
||||
}
|
||||
|
||||
.tab-icon {
|
||||
font-size: 16px;
|
||||
display: block;
|
||||
margin-bottom: 1px;
|
||||
}
|
||||
|
||||
.tab-label {
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
.empty-tab {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 14px;
|
||||
text-align: center;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.chapter-list > li {
|
||||
padding: 0;
|
||||
margin: 0 8px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.chapter-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
padding: 6px 12px;
|
||||
border-radius: 8px;
|
||||
transition: background 0.2s;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
&.has-subchapters {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: rgba(74, 144, 226, 0.3);
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
|
||||
&:hover {
|
||||
background: rgba(74, 144, 226, 0.4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.accordion-icon {
|
||||
margin-left: auto;
|
||||
transition: transform 0.2s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
i {
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.subchapter-list {
|
||||
list-style: none;
|
||||
padding-left: 0;
|
||||
margin: 0;
|
||||
|
||||
li {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
import {Component, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {BookMark} from '../../../../../shared/service/book-mark.service';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {TocItem} from 'epubjs';
|
||||
|
||||
@Component({
|
||||
selector: 'app-reader-sidebar',
|
||||
standalone: true,
|
||||
templateUrl: './reader-sidebar.component.html',
|
||||
styleUrls: ['./reader-sidebar.component.scss'],
|
||||
imports: [CommonModule]
|
||||
})
|
||||
export class ReaderSidebarComponent implements OnChanges {
|
||||
@Input() bookId: number | null = null;
|
||||
@Input() coverUpdatedOn: string | undefined;
|
||||
@Input() bookTitle: string = '';
|
||||
@Input() bookAuthors: string = '';
|
||||
@Input() chapters: TocItem[] = [];
|
||||
@Input() bookmarks: BookMark[] = [];
|
||||
@Input() currentChapterHref: string | null = null;
|
||||
@Output() close = new EventEmitter<void>();
|
||||
@Output() chapterClick = new EventEmitter<string>();
|
||||
@Output() bookmarkClick = new EventEmitter<string>();
|
||||
@Output() deleteBookmark = new EventEmitter<number>();
|
||||
@Output() coverClick = new EventEmitter<void>();
|
||||
|
||||
private urlHelperService = inject(UrlHelperService);
|
||||
|
||||
activeTab: 'chapters' | 'bookmarks' | 'annotation' = 'chapters';
|
||||
closing = false;
|
||||
bookCoverUrl: string | null = null;
|
||||
|
||||
expandedChapters = new Set<string>();
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['bookId'] || changes['coverUpdatedOn']) {
|
||||
this.bookCoverUrl = this.bookId
|
||||
? this.urlHelperService.getThumbnailUrl(this.bookId, this.coverUpdatedOn)
|
||||
: null;
|
||||
}
|
||||
|
||||
if (changes['currentChapterHref']) {
|
||||
if (this.currentChapterHref) {
|
||||
this.autoExpandCurrentChapter();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private autoExpandCurrentChapter(): void {
|
||||
if (!this.currentChapterHref) return;
|
||||
|
||||
const expandParents = (items: TocItem[], parents: string[] = []): boolean => {
|
||||
for (const item of items) {
|
||||
const currentParents = [...parents, item.href];
|
||||
|
||||
const normalizedItemHref = item.href.split('#')[0].replace(/^\//, '');
|
||||
const normalizedCurrentHref = this.currentChapterHref!.split('#')[0].replace(/^\//, '');
|
||||
|
||||
if (normalizedItemHref === normalizedCurrentHref || item.href === this.currentChapterHref) {
|
||||
parents.forEach(parentHref => this.expandedChapters.add(parentHref));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (item.subitems?.length) {
|
||||
if (expandParents(item.subitems, currentParents)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
expandParents(this.chapters);
|
||||
}
|
||||
|
||||
private closeWithAnimation(callback?: () => void) {
|
||||
this.closing = true;
|
||||
setTimeout(() => {
|
||||
this.closing = false;
|
||||
if (callback) callback();
|
||||
this.close.emit();
|
||||
}, 250);
|
||||
}
|
||||
|
||||
onChapterClick(href: string) {
|
||||
this.closeWithAnimation(() => this.chapterClick.emit(href));
|
||||
}
|
||||
|
||||
onBookmarkClick(cfi: string) {
|
||||
this.closeWithAnimation(() => this.bookmarkClick.emit(cfi));
|
||||
}
|
||||
|
||||
onDeleteBookmark(event: MouseEvent, bookmarkId: number) {
|
||||
event.stopPropagation();
|
||||
this.deleteBookmark.emit(bookmarkId);
|
||||
}
|
||||
|
||||
onCoverClick() {
|
||||
this.closeWithAnimation(() => this.coverClick.emit());
|
||||
}
|
||||
|
||||
onOverlayClick() {
|
||||
this.closeWithAnimation();
|
||||
}
|
||||
|
||||
toggleChapterExpand(href: string) {
|
||||
if (this.expandedChapters.has(href)) {
|
||||
this.expandedChapters.delete(href);
|
||||
} else {
|
||||
this.expandedChapters.add(href);
|
||||
}
|
||||
}
|
||||
|
||||
isChapterExpanded(href: string): boolean {
|
||||
return this.expandedChapters.has(href);
|
||||
}
|
||||
|
||||
isChapterActive(href: string): boolean {
|
||||
if (!this.currentChapterHref) return false;
|
||||
|
||||
const normalizedItemHref = href.split('#')[0].replace(/^\//, '');
|
||||
const normalizedCurrentHref = this.currentChapterHref.split('#')[0].replace(/^\//, '');
|
||||
|
||||
return normalizedItemHref === normalizedCurrentHref || href === this.currentChapterHref;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Observable, of} from 'rxjs';
|
||||
import {catchError, map} from 'rxjs/operators';
|
||||
import {BookMarkService} from '../../../../shared/service/book-mark.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
@Injectable()
|
||||
export class ReaderBookmarkService {
|
||||
private currentCFI: string | null = null;
|
||||
private currentChapterName: string | null = null;
|
||||
|
||||
private bookMarkService = inject(BookMarkService);
|
||||
private messageService = inject(MessageService);
|
||||
|
||||
|
||||
updateCurrentPosition(cfi: string, chapterName?: string): void {
|
||||
this.currentCFI = cfi;
|
||||
if (chapterName) {
|
||||
this.currentChapterName = chapterName;
|
||||
}
|
||||
}
|
||||
|
||||
createBookmarkAtCurrentPosition(bookId: number): Observable<boolean> {
|
||||
const cfi = this.currentCFI;
|
||||
if (!cfi) {
|
||||
console.error('Could not get current CFI - please navigate to a page first');
|
||||
return of(false);
|
||||
}
|
||||
|
||||
const title = this.currentChapterName || 'Bookmark';
|
||||
|
||||
return this.bookMarkService.createBookmark({bookId, cfi, title}).pipe(
|
||||
map(() => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Bookmark Added',
|
||||
detail: 'Your bookmark was added successfully.'
|
||||
});
|
||||
return true;
|
||||
}),
|
||||
catchError(error => {
|
||||
const isDuplicate = error?.status === 409;
|
||||
this.messageService.add(
|
||||
isDuplicate
|
||||
? {
|
||||
severity: 'warn',
|
||||
summary: 'Bookmark Already Exists',
|
||||
detail: 'You already have a bookmark at this location.'
|
||||
}
|
||||
: {
|
||||
severity: 'error',
|
||||
summary: 'Unable to Add Bookmark',
|
||||
detail: 'Something went wrong while adding the bookmark. Please try again.'
|
||||
}
|
||||
);
|
||||
return of(false);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.currentCFI = null;
|
||||
this.currentChapterName = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {defer, from, Observable, of} from 'rxjs';
|
||||
import {switchMap} from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReaderLoaderService {
|
||||
private scriptLoaded = false;
|
||||
|
||||
loadFoliateScript(): Observable<void> {
|
||||
if (this.scriptLoaded || customElements.get('foliate-view')) {
|
||||
return of(undefined);
|
||||
}
|
||||
|
||||
return defer(() => new Observable<void>(observer => {
|
||||
const script = document.createElement('script');
|
||||
script.type = 'module';
|
||||
script.src = '/assets/foliate/view.js';
|
||||
script.onload = () => {
|
||||
this.scriptLoaded = true;
|
||||
setTimeout(() => {
|
||||
observer.next();
|
||||
observer.complete();
|
||||
}, 100);
|
||||
};
|
||||
script.onerror = () => observer.error(new Error('Failed to load foliate.js'));
|
||||
document.head.appendChild(script);
|
||||
}));
|
||||
}
|
||||
|
||||
waitForCustomElement(): Observable<void> {
|
||||
return defer(() => from(customElements.whenDefined('foliate-view'))).pipe(
|
||||
switchMap(() => of(undefined))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, forkJoin, Observable} from 'rxjs';
|
||||
import {map, tap} from 'rxjs/operators';
|
||||
import {Theme, themes} from './reader-themes';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {EpubCustomFontService} from '../../epub-reader/service/epub-custom-font.service';
|
||||
|
||||
export interface ReaderState {
|
||||
lineHeight: number;
|
||||
justify: boolean;
|
||||
hyphenate: boolean;
|
||||
maxColumnCount: number;
|
||||
gap: number;
|
||||
fontSize: number;
|
||||
theme: Theme;
|
||||
maxInlineSize: number;
|
||||
maxBlockSize: number;
|
||||
fontFamily: string | null;
|
||||
isDark: boolean;
|
||||
flow: 'paginated' | 'scrolled';
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReaderStateService {
|
||||
private epubCustomFontService = inject(EpubCustomFontService);
|
||||
|
||||
private readonly BASE_FONTS = [
|
||||
{name: 'Publisher\'s', value: null},
|
||||
{name: 'Serif', value: 'serif'},
|
||||
{name: 'Sans-Serif', value: 'sans-serif'},
|
||||
{name: 'Monospace', value: 'monospace'},
|
||||
{name: 'Cursive', value: 'cursive'},
|
||||
];
|
||||
|
||||
private readonly defaultState: ReaderState = {
|
||||
lineHeight: 1.5,
|
||||
justify: true,
|
||||
hyphenate: true,
|
||||
maxColumnCount: 2,
|
||||
gap: 0.05,
|
||||
fontSize: 16,
|
||||
theme: {
|
||||
...themes[0],
|
||||
fg: themes[0].dark.fg,
|
||||
bg: themes[0].dark.bg,
|
||||
link: themes[0].dark.link,
|
||||
},
|
||||
maxInlineSize: 720,
|
||||
maxBlockSize: 1440,
|
||||
fontFamily: null,
|
||||
isDark: true,
|
||||
flow: 'paginated',
|
||||
};
|
||||
|
||||
private stateSubject = new BehaviorSubject<ReaderState>(this.defaultState);
|
||||
public state$ = this.stateSubject.asObservable();
|
||||
|
||||
get currentState(): ReaderState {
|
||||
return this.stateSubject.value;
|
||||
}
|
||||
|
||||
readonly themes = themes;
|
||||
private fontsSubject = new BehaviorSubject<Array<{ name: string; value: string | null }>>(this.BASE_FONTS);
|
||||
|
||||
get fonts(): Array<{ name: string; value: string | null }> {
|
||||
return this.fontsSubject.value;
|
||||
}
|
||||
|
||||
constructor(private bookService: BookService, private userService: UserService) {
|
||||
this.loadCustomFontsIntoList();
|
||||
}
|
||||
|
||||
private loadCustomFontsIntoList(): void {
|
||||
const customFonts = this.epubCustomFontService.getCustomFonts();
|
||||
const customFontOptions = customFonts.map(font => ({
|
||||
name: font.fontName.replace(/\.(ttf|otf|woff|woff2)$/i, ''),
|
||||
value: `custom:${font.id}`
|
||||
}));
|
||||
|
||||
const updatedFonts = [
|
||||
...this.fontsSubject.value,
|
||||
...customFontOptions
|
||||
];
|
||||
|
||||
this.fontsSubject.next(updatedFonts);
|
||||
}
|
||||
|
||||
refreshCustomFonts(): void {
|
||||
this.fontsSubject.next([...this.BASE_FONTS]);
|
||||
this.loadCustomFontsIntoList();
|
||||
}
|
||||
|
||||
initializeState(bookId: number): Observable<void> {
|
||||
return forkJoin([
|
||||
this.userService.getMyself(),
|
||||
this.bookService.getBookSetting(bookId)
|
||||
]).pipe(
|
||||
tap(([myself, bookSetting]) => {
|
||||
const settingScope = myself.userSettings.perBookSetting.epub;
|
||||
const globalSettings = myself.userSettings.ebookReaderSetting;
|
||||
const individualSetting = bookSetting?.ebookSettings;
|
||||
const settings = settingScope === 'Global' ? globalSettings : (individualSetting || globalSettings);
|
||||
const newState: Partial<ReaderState> = {};
|
||||
if (settings.fontSize != null) newState.fontSize = settings.fontSize;
|
||||
if (settings.lineHeight != null) newState.lineHeight = settings.lineHeight;
|
||||
|
||||
if (settings.fontFamily != null) {
|
||||
if (settings.fontFamily.startsWith('custom:')) {
|
||||
newState.fontFamily = settings.fontFamily;
|
||||
} else {
|
||||
const numericId = parseInt(settings.fontFamily, 10);
|
||||
if (!isNaN(numericId) && numericId.toString() === settings.fontFamily) {
|
||||
newState.fontFamily = `custom:${numericId}`;
|
||||
} else {
|
||||
newState.fontFamily = settings.fontFamily;
|
||||
}
|
||||
}
|
||||
} else if ((settings as any).customFontId != null) {
|
||||
newState.fontFamily = `custom:${(settings as any).customFontId}`;
|
||||
}
|
||||
|
||||
if (settings.gap != null) newState.gap = settings.gap;
|
||||
if (settings.hyphenate != null) newState.hyphenate = settings.hyphenate;
|
||||
if (settings.justify != null) newState.justify = settings.justify;
|
||||
if (settings.maxColumnCount != null) newState.maxColumnCount = settings.maxColumnCount;
|
||||
if (settings.maxInlineSize != null) newState.maxInlineSize = settings.maxInlineSize;
|
||||
if (settings.maxBlockSize != null) newState.maxBlockSize = settings.maxBlockSize;
|
||||
if (settings.isDark != null) newState.isDark = settings.isDark;
|
||||
if (settings.flow) newState.flow = settings.flow;
|
||||
if (settings.theme) {
|
||||
const theme = this.themes.find(t => t.name === settings.theme);
|
||||
if (theme) {
|
||||
newState.theme = {
|
||||
...theme,
|
||||
fg: settings.isDark ? theme.dark.fg : theme.light.fg,
|
||||
bg: settings.isDark ? theme.dark.bg : theme.light.bg,
|
||||
link: settings.isDark ? theme.dark.link : theme.light.link,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (Object.keys(newState).length > 0) {
|
||||
this.updateState(newState);
|
||||
}
|
||||
}),
|
||||
map(() => void 0)
|
||||
);
|
||||
}
|
||||
|
||||
updateLineHeight(delta: number): void {
|
||||
const current = this.currentState.lineHeight;
|
||||
const newValue = Math.max(0.8, Math.min(3, current + delta));
|
||||
this.updateState({lineHeight: newValue});
|
||||
}
|
||||
|
||||
updateMaxColumnCount(delta: number): void {
|
||||
const current = this.currentState.maxColumnCount;
|
||||
const newValue = Math.max(1, Math.min(10, current + delta));
|
||||
this.updateState({maxColumnCount: newValue});
|
||||
}
|
||||
|
||||
updateGap(delta: number): void {
|
||||
const current = this.currentState.gap;
|
||||
const newValue = Math.max(0, Math.min(0.5, current + delta));
|
||||
this.updateState({gap: newValue});
|
||||
}
|
||||
|
||||
toggleJustify(): void {
|
||||
this.updateState({justify: !this.currentState.justify});
|
||||
}
|
||||
|
||||
toggleHyphenate(): void {
|
||||
this.updateState({hyphenate: !this.currentState.hyphenate});
|
||||
}
|
||||
|
||||
updateFontSize(delta: number): void {
|
||||
const newFontSize = Math.max(10, Math.min(32, this.currentState.fontSize + delta));
|
||||
this.updateState({fontSize: newFontSize});
|
||||
}
|
||||
|
||||
setTheme(theme: Theme): void {
|
||||
this.updateState({theme});
|
||||
}
|
||||
|
||||
setFontFamily(font: string | null): void {
|
||||
if (font === null) {
|
||||
this.updateState({fontFamily: null});
|
||||
} else if (!font.includes(':') && !isNaN(parseInt(font, 10)) && parseInt(font, 10).toString() === font) {
|
||||
this.updateState({fontFamily: `custom:${font}`});
|
||||
} else {
|
||||
this.updateState({fontFamily: font});
|
||||
}
|
||||
}
|
||||
|
||||
updateMaxInlineSize(delta: number): void {
|
||||
const newValue = Math.max(400, Math.min(1600, this.currentState.maxInlineSize + delta));
|
||||
this.updateState({maxInlineSize: newValue});
|
||||
}
|
||||
|
||||
updateMaxBlockSize(delta: number): void {
|
||||
const newValue = Math.max(600, Math.min(2400, this.currentState.maxBlockSize + delta));
|
||||
this.updateState({maxBlockSize: newValue});
|
||||
}
|
||||
|
||||
toggleDarkMode() {
|
||||
const currentTheme = this.currentState.theme;
|
||||
const newIsDark = !this.currentState.isDark;
|
||||
const newTheme = {
|
||||
...currentTheme,
|
||||
fg: newIsDark ? currentTheme.dark.fg : currentTheme.light.fg,
|
||||
bg: newIsDark ? currentTheme.dark.bg : currentTheme.light.bg,
|
||||
link: newIsDark ? currentTheme.dark.link : currentTheme.light.link,
|
||||
};
|
||||
this.updateState({theme: newTheme, isDark: newIsDark});
|
||||
}
|
||||
|
||||
setThemeByName(themeName: string) {
|
||||
const theme = this.themes.find(t => t.name === themeName);
|
||||
if (theme) {
|
||||
const newTheme = {
|
||||
...theme,
|
||||
fg: this.currentState.isDark ? theme.dark.fg : theme.light.fg,
|
||||
bg: this.currentState.isDark ? theme.dark.bg : theme.light.bg,
|
||||
link: this.currentState.isDark ? theme.dark.link : theme.light.link,
|
||||
};
|
||||
this.setTheme(newTheme);
|
||||
}
|
||||
}
|
||||
|
||||
setFlow(flow: 'paginated' | 'scrolled'): void {
|
||||
this.updateState({ flow });
|
||||
}
|
||||
|
||||
private updateState(partial: Partial<ReaderState>): void {
|
||||
this.stateSubject.next({...this.currentState, ...partial});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ReaderState} from './reader-state.service';
|
||||
import {EpubCustomFontService} from '../../epub-reader/service/epub-custom-font.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReaderStyleService {
|
||||
private epubCustomFontService = inject(EpubCustomFontService);
|
||||
|
||||
generateCSS(state: ReaderState): string {
|
||||
const {lineHeight, justify, hyphenate, fontSize, theme, fontFamily} = state;
|
||||
const userStylesheet = '';
|
||||
const overrideFont = false;
|
||||
const mediaActiveClass = 'media-active';
|
||||
|
||||
let fontFaceRule = '';
|
||||
let actualFontFamily = null;
|
||||
|
||||
if (fontFamily !== null) {
|
||||
const customFontId = this.parseCustomFontId(fontFamily);
|
||||
if (customFontId !== null) {
|
||||
const customFont = this.epubCustomFontService.getCustomFontById(customFontId);
|
||||
const blobUrl = this.epubCustomFontService.getBlobUrl(customFontId);
|
||||
if (customFont && blobUrl) {
|
||||
const sanitizedFontName = this.epubCustomFontService.sanitizeFontName(customFont.fontName);
|
||||
actualFontFamily = `"${sanitizedFontName}", sans-serif`;
|
||||
fontFaceRule = `@font-face {
|
||||
font-family: "${sanitizedFontName}";
|
||||
src: url("${blobUrl}") format("truetype");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}`;
|
||||
}
|
||||
} else {
|
||||
actualFontFamily = fontFamily;
|
||||
}
|
||||
}
|
||||
|
||||
const fontFamilyRule = actualFontFamily ? `
|
||||
body {
|
||||
font-family: ${actualFontFamily} !important;
|
||||
}
|
||||
body * {
|
||||
font-family: inherit !important;
|
||||
}` : '';
|
||||
|
||||
return `
|
||||
${fontFaceRule}
|
||||
@namespace epub "http://www.idpf.org/2007/ops";
|
||||
@media print {
|
||||
html {
|
||||
column-width: auto !important;
|
||||
height: auto !important;
|
||||
width: auto !important;
|
||||
}
|
||||
}
|
||||
@media screen {
|
||||
html {
|
||||
color-scheme: light dark;
|
||||
color: ${theme.fg || theme.light.fg};
|
||||
font-size: ${fontSize}px;
|
||||
}${fontFamilyRule}
|
||||
a:any-link {
|
||||
color: ${theme.link || theme.light.link};
|
||||
text-decoration-color: light-dark(
|
||||
color-mix(in srgb, currentColor 20%, transparent),
|
||||
color-mix(in srgb, currentColor 40%, transparent));
|
||||
text-underline-offset: .1em;
|
||||
}
|
||||
a:any-link:hover {
|
||||
text-decoration-color: unset;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html {
|
||||
color: ${theme.fg || theme.dark.fg};
|
||||
}
|
||||
a:any-link {
|
||||
color: ${theme.link || theme.dark.link};
|
||||
}
|
||||
}
|
||||
aside[epub|type~="footnote"] {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
html {
|
||||
line-height: ${lineHeight};
|
||||
hanging-punctuation: allow-end last;
|
||||
orphans: 2;
|
||||
widows: 2;
|
||||
}
|
||||
[align="left"] { text-align: left; }
|
||||
[align="right"] { text-align: right; }
|
||||
[align="center"] { text-align: center; }
|
||||
[align="justify"] { text-align: justify; }
|
||||
:is(hgroup, header) p {
|
||||
text-align: unset;
|
||||
hyphens: unset;
|
||||
}
|
||||
h1, h2, h3, h4, h5, h6, hgroup, th {
|
||||
text-wrap: balance;
|
||||
}
|
||||
pre {
|
||||
white-space: pre-wrap !important;
|
||||
tab-size: 2;
|
||||
}
|
||||
@media screen and (prefers-color-scheme: light) {
|
||||
${(theme.bg || theme.light.bg) !== '#ffffff' ? `
|
||||
html, body {
|
||||
color: ${theme.fg || theme.light.fg} !important;
|
||||
background: none !important;
|
||||
}
|
||||
body * {
|
||||
color: inherit !important;
|
||||
border-color: currentColor !important;
|
||||
background-color: ${theme.bg || theme.light.bg} !important;
|
||||
}
|
||||
a:any-link {
|
||||
color: ${theme.link || theme.light.link} !important;
|
||||
}
|
||||
svg, img {
|
||||
background-color: transparent !important;
|
||||
mix-blend-mode: multiply;
|
||||
}
|
||||
.${mediaActiveClass}, .${mediaActiveClass} * {
|
||||
color: ${theme.fg || theme.light.fg} !important;
|
||||
background: color-mix(in hsl, ${theme.fg || theme.light.fg}, #fff 50%) !important;
|
||||
background: color-mix(in hsl, ${theme.fg || theme.light.fg}, ${theme.bg || theme.light.bg} 85%) !important;
|
||||
}` : ''}
|
||||
}
|
||||
@media screen and (prefers-color-scheme: dark) {
|
||||
|
||||
html, body {
|
||||
color: ${theme.fg || theme.dark.fg} !important;
|
||||
background: none !important;
|
||||
}
|
||||
body * {
|
||||
color: inherit !important;
|
||||
border-color: currentColor !important;
|
||||
background-color: ${theme.bg || theme.dark.bg} !important;
|
||||
}
|
||||
a:any-link {
|
||||
color: ${theme.link || theme.dark.link} !important;
|
||||
}
|
||||
.${mediaActiveClass}, .${mediaActiveClass} * {
|
||||
color: ${theme.fg || theme.dark.fg} !important;
|
||||
background: color-mix(in hsl, ${theme.fg || theme.dark.fg}, #000 50%) !important;
|
||||
background: color-mix(in hsl, ${theme.fg || theme.dark.fg}, ${theme.bg || theme.dark.bg} 75%) !important;
|
||||
}
|
||||
}
|
||||
p, li, blockquote, dd {
|
||||
line-height: ${lineHeight};
|
||||
text-align: ${justify ? 'justify' : 'start'} !important;
|
||||
hyphens: ${hyphenate ? 'auto' : 'none'};
|
||||
}
|
||||
${overrideFont ? '' : ''}
|
||||
${userStylesheet}
|
||||
`;
|
||||
}
|
||||
|
||||
private parseCustomFontId(fontFamily: string): number | null {
|
||||
if (fontFamily.startsWith('custom:')) {
|
||||
const id = parseInt(fontFamily.substring(7), 10);
|
||||
return !isNaN(id) ? id : null;
|
||||
}
|
||||
|
||||
const id = parseInt(fontFamily, 10);
|
||||
return !isNaN(id) && id.toString() === fontFamily ? id : null;
|
||||
}
|
||||
|
||||
applyStylesToRenderer(renderer: any, state: ReaderState): void {
|
||||
if (!renderer) return;
|
||||
|
||||
renderer.setAttribute('max-column-count', state.maxColumnCount);
|
||||
renderer.setAttribute('gap', `${state.gap * 100}%`);
|
||||
renderer.setAttribute('max-inline-size', `${state.maxInlineSize}px`);
|
||||
renderer.setAttribute('max-block-size', `${state.maxBlockSize}px`);
|
||||
if (typeof renderer.setStyles === 'function') {
|
||||
const css = this.generateCSS(state);
|
||||
renderer.setStyles(css);
|
||||
}
|
||||
|
||||
if (state.flow === 'paginated') {
|
||||
renderer.setAttribute('margin', '40px');
|
||||
} else {
|
||||
renderer.removeAttribute('margin');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
export interface ThemeMode {
|
||||
fg: string;
|
||||
bg: string;
|
||||
link: string;
|
||||
}
|
||||
|
||||
export interface Theme {
|
||||
name: string;
|
||||
label: string;
|
||||
light: ThemeMode;
|
||||
dark: ThemeMode;
|
||||
fg?: string;
|
||||
bg?: string;
|
||||
link?: string;
|
||||
}
|
||||
|
||||
export const themes: Theme[] = [
|
||||
{
|
||||
name: 'default', label: 'Default',
|
||||
light: {fg: '#000000', bg: '#ffffff', link: '#0066cc'},
|
||||
dark: {fg: '#e0e0e0', bg: '#222222', link: '#77bbee'},
|
||||
},
|
||||
{
|
||||
name: 'gray', label: 'Gray',
|
||||
light: {fg: '#222222', bg: '#e0e0e0', link: '#4488cc'},
|
||||
dark: {fg: '#c6c6c6', bg: '#444444', link: '#88ccee'},
|
||||
},
|
||||
{
|
||||
name: 'sepia', label: 'Sepia',
|
||||
light: {fg: '#5b4636', bg: '#f1e8d0', link: '#008b8b'},
|
||||
dark: {fg: '#ffd595', bg: '#342e25', link: '#48d1cc'},
|
||||
},
|
||||
{
|
||||
name: 'crimson', label: 'Crimson',
|
||||
light: {fg: '#212529', bg: '#ffffff', link: '#dd0031'},
|
||||
dark: {fg: '#dee2e6', bg: '#343a40', link: '#ff4081'},
|
||||
},
|
||||
{
|
||||
name: 'meadow', label: 'Meadow',
|
||||
light: {fg: '#232c16', bg: '#d7dbbd', link: '#177b4d'},
|
||||
dark: {fg: '#d8deba', bg: '#333627', link: '#a6d608'},
|
||||
},
|
||||
{
|
||||
name: 'rosewood', label: 'Rosewood',
|
||||
light: {fg: '#4e1609', bg: '#f0d1d5', link: '#de3838'},
|
||||
dark: {fg: '#e5c4c8', bg: '#462f32', link: '#ff646e'},
|
||||
},
|
||||
{
|
||||
name: 'azure', label: 'Azure',
|
||||
light: {fg: '#262d48', bg: '#cedef5', link: '#2d53e5'},
|
||||
dark: {fg: '#babee1', bg: '#282e47', link: '#ff646e'},
|
||||
},
|
||||
{
|
||||
name: 'dawnlight', label: 'Dawnlight',
|
||||
light: {fg: '#586e75', bg: '#fdf6e3', link: '#268bd2'},
|
||||
dark: {fg: '#93a1a1', bg: '#002b36', link: '#268bd2'},
|
||||
},
|
||||
{
|
||||
name: 'ember', label: 'Ember',
|
||||
light: {fg: '#3c3836', bg: '#fbf1c7', link: '#076678'},
|
||||
dark: {fg: '#ebdbb2', bg: '#282828', link: '#83a598'},
|
||||
},
|
||||
{
|
||||
name: 'aurora', label: 'Aurora',
|
||||
light: {fg: '#2e3440', bg: '#eceff4', link: '#5e81ac'},
|
||||
dark: {fg: '#d8dee9', bg: '#2e3440', link: '#88c0d0'},
|
||||
},
|
||||
{
|
||||
name: 'ocean', label: 'Ocean',
|
||||
light: {fg: '#0a4d4d', bg: '#e0f7fa', link: '#00838f'},
|
||||
dark: {fg: '#b2dfdb', bg: '#263238', link: '#4dd0e1'},
|
||||
},
|
||||
{
|
||||
name: 'mist', label: 'Mist',
|
||||
light: {fg: '#4a148c', bg: '#f3e5f5', link: '#7b1fa2'},
|
||||
dark: {fg: '#c7b6dd', bg: '#3a3150', link: '#b39ddb'},
|
||||
},
|
||||
];
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {defer, from, Observable, of, Subject, throwError, timer} from 'rxjs';
|
||||
import {catchError, map, switchMap} from 'rxjs/operators';
|
||||
import {PageInfo, ReaderHeaderFooterUtil, ThemeInfo} from '../utils/reader-header-footer.util';
|
||||
|
||||
export interface ViewEvent {
|
||||
type: 'load' | 'relocate' | 'error' | 'middle-single-tap';
|
||||
detail?: any;
|
||||
}
|
||||
|
||||
interface TocItem {
|
||||
label: string;
|
||||
href: string;
|
||||
subitems?: TocItem[];
|
||||
}
|
||||
|
||||
export interface BookMetadata {
|
||||
title?: string;
|
||||
authors?: string[];
|
||||
language?: string;
|
||||
publisher?: string;
|
||||
description?: string;
|
||||
identifier?: string;
|
||||
coverUrl?: string;
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReaderViewManagerService {
|
||||
private readonly DOUBLE_CLICK_INTERVAL_MS = 300;
|
||||
private readonly LONG_HOLD_THRESHOLD_MS = 500;
|
||||
private readonly LEFT_ZONE_PERCENT = 0.3;
|
||||
private readonly RIGHT_ZONE_PERCENT = 0.7;
|
||||
|
||||
private view: any;
|
||||
private isNavigating = false;
|
||||
private lastClickTime = 0;
|
||||
private lastClickZone: 'left' | 'middle' | 'right' | null = null;
|
||||
private longHoldTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
private keydownHandler?: (event: KeyboardEvent) => void;
|
||||
private clickedDocs = new WeakSet<Document>();
|
||||
|
||||
private eventSubject = new Subject<ViewEvent>();
|
||||
public events$ = this.eventSubject.asObservable();
|
||||
|
||||
createView(container: HTMLElement): void {
|
||||
this.view = document.createElement('foliate-view');
|
||||
this.view.style.width = '100%';
|
||||
this.view.style.height = '100%';
|
||||
this.view.style.display = 'block';
|
||||
container.appendChild(this.view);
|
||||
|
||||
this.attachEventListeners();
|
||||
this.attachKeyboardHandler();
|
||||
}
|
||||
|
||||
loadEpub(epubPath: string): Observable<void> {
|
||||
if (!this.view) {
|
||||
return throwError(() => new Error('View not created'));
|
||||
}
|
||||
|
||||
return timer(100).pipe(
|
||||
switchMap(() => from(fetch(epubPath))),
|
||||
switchMap(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`EPUB not found: ${response.status}`);
|
||||
}
|
||||
return from(response.blob());
|
||||
}),
|
||||
switchMap(blob => {
|
||||
const file = new File([blob], epubPath.split('/').pop() || 'book.epub', {
|
||||
type: 'application/epub+zip'
|
||||
});
|
||||
return from(this.view.open(file) as Promise<void>);
|
||||
}),
|
||||
map(() => undefined),
|
||||
catchError(err => throwError(() => err))
|
||||
);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
if (this.keydownHandler) {
|
||||
document.removeEventListener('keydown', this.keydownHandler);
|
||||
this.keydownHandler = undefined;
|
||||
}
|
||||
this.view?.remove();
|
||||
this.view = null;
|
||||
}
|
||||
|
||||
goTo(target?: string | number | null): Observable<void> {
|
||||
const resolvedTarget = target ?? 0;
|
||||
if (!this.view) {
|
||||
return of(undefined);
|
||||
}
|
||||
return defer(() =>
|
||||
from(this.view.goTo(resolvedTarget) as Promise<void>)
|
||||
).pipe(
|
||||
map(() => undefined)
|
||||
);
|
||||
}
|
||||
|
||||
goToSection(index: number): Observable<void> {
|
||||
return this.goTo(index);
|
||||
}
|
||||
|
||||
goToFraction(fraction: number): Observable<void> {
|
||||
if (!this.view) {
|
||||
return of(undefined);
|
||||
}
|
||||
return defer(() => from(this.view.goToFraction(fraction) as Promise<void>)).pipe(
|
||||
map(() => undefined)
|
||||
);
|
||||
}
|
||||
|
||||
prev(): void {
|
||||
this.view?.prev();
|
||||
}
|
||||
|
||||
next(): void {
|
||||
this.view?.next();
|
||||
}
|
||||
|
||||
getRenderer(): any {
|
||||
return this.view?.renderer;
|
||||
}
|
||||
|
||||
updateHeadersAndFooters(chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void {
|
||||
const renderer = this.getRenderer();
|
||||
ReaderHeaderFooterUtil.updateHeadersAndFooters(renderer, chapterName, pageInfo, theme);
|
||||
}
|
||||
|
||||
getChapters(): TocItem[] {
|
||||
if (!this.view?.book?.toc) return [];
|
||||
|
||||
const mapToc = (items: any[]): TocItem[] =>
|
||||
items.map(item => ({
|
||||
label: item.label,
|
||||
href: item.href,
|
||||
subitems: item.subitems?.length ? mapToc(item.subitems) : undefined
|
||||
}));
|
||||
|
||||
return mapToc(this.view.book.toc);
|
||||
}
|
||||
|
||||
getSectionFractions(): number[] {
|
||||
if (!this.view?.getSectionFractions) return [];
|
||||
return this.view.getSectionFractions();
|
||||
}
|
||||
|
||||
getMetadata(): Observable<BookMetadata> {
|
||||
if (!this.view?.book?.metadata) {
|
||||
return of({});
|
||||
}
|
||||
|
||||
const {metadata} = this.view.book;
|
||||
|
||||
return this.getCoverUrl().pipe(
|
||||
map(coverUrl => ({
|
||||
title: metadata.title,
|
||||
authors: metadata.authors,
|
||||
language: metadata.language,
|
||||
publisher: metadata.publisher,
|
||||
description: metadata.description,
|
||||
identifier: metadata.identifier,
|
||||
coverUrl,
|
||||
...metadata
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
getCover(): Observable<Blob | null> {
|
||||
if (!this.view?.book?.getCover) {
|
||||
return of(null);
|
||||
}
|
||||
return defer(() => {
|
||||
const coverPromise = this.view.book.getCover();
|
||||
return coverPromise ? from(coverPromise as Promise<Blob | null>) : of(null);
|
||||
});
|
||||
}
|
||||
|
||||
getCoverUrl(): Observable<string | null> {
|
||||
return this.getCover().pipe(
|
||||
map(blob => blob ? URL.createObjectURL(blob) : null)
|
||||
);
|
||||
}
|
||||
|
||||
private attachEventListeners(): void {
|
||||
this.view.addEventListener('load', (e: any) => {
|
||||
this.eventSubject.next({type: 'load', detail: e.detail});
|
||||
if (e.detail?.doc) {
|
||||
if (this.keydownHandler) {
|
||||
e.detail.doc.addEventListener('keydown', this.keydownHandler);
|
||||
}
|
||||
this.attachIframeEventHandlers(e.detail.doc);
|
||||
}
|
||||
});
|
||||
|
||||
this.view.addEventListener('relocate', (e: any) => {
|
||||
this.eventSubject.next({type: 'relocate', detail: e.detail});
|
||||
});
|
||||
|
||||
this.view.addEventListener('error', (e: any) => {
|
||||
this.eventSubject.next({type: 'error', detail: e.detail});
|
||||
});
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.data?.type === 'iframe-click') {
|
||||
this.handleIframeClickMessage(event.data);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private attachKeyboardHandler(): void {
|
||||
this.keydownHandler = (event: KeyboardEvent) => {
|
||||
const k = event.key;
|
||||
if (k === 'ArrowLeft' || k === 'h' || k === 'PageUp') {
|
||||
this.prev();
|
||||
event.preventDefault();
|
||||
} else if (k === 'ArrowRight' || k === 'l' || k === 'PageDown') {
|
||||
this.next();
|
||||
event.preventDefault();
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', this.keydownHandler);
|
||||
}
|
||||
|
||||
private attachIframeEventHandlers(doc: Document): void {
|
||||
if (this.clickedDocs.has(doc)) {
|
||||
return;
|
||||
}
|
||||
this.clickedDocs.add(doc);
|
||||
|
||||
doc.addEventListener('mousedown', (event: MouseEvent) => {
|
||||
this.longHoldTimeout = setTimeout(() => {
|
||||
this.longHoldTimeout = null;
|
||||
}, this.LONG_HOLD_THRESHOLD_MS);
|
||||
}, true);
|
||||
|
||||
doc.addEventListener('click', (event: MouseEvent) => {
|
||||
const iframe = doc.defaultView?.frameElement as HTMLIFrameElement | null;
|
||||
if (!iframe) return;
|
||||
|
||||
const iframeRect = iframe.getBoundingClientRect();
|
||||
const viewportX = iframeRect.left + event.clientX;
|
||||
const viewportY = iframeRect.top + event.clientY;
|
||||
|
||||
window.postMessage({
|
||||
type: 'iframe-click',
|
||||
clientX: viewportX,
|
||||
clientY: viewportY,
|
||||
iframeLeft: iframeRect.left,
|
||||
iframeWidth: iframeRect.width,
|
||||
eventClientX: event.clientX,
|
||||
target: (event.target as HTMLElement)?.tagName
|
||||
}, '*');
|
||||
}, true);
|
||||
}
|
||||
|
||||
private handleIframeClickMessage(data: any): void {
|
||||
const now = Date.now();
|
||||
const timeSinceLastClick = now - this.lastClickTime;
|
||||
|
||||
const viewRect = this.view.getBoundingClientRect();
|
||||
const x = data.clientX - viewRect.left;
|
||||
const width = viewRect.width;
|
||||
|
||||
const leftThreshold = width * this.LEFT_ZONE_PERCENT;
|
||||
const rightThreshold = width * this.RIGHT_ZONE_PERCENT;
|
||||
|
||||
let currentZone: 'left' | 'middle' | 'right';
|
||||
if (x < leftThreshold) {
|
||||
currentZone = 'left';
|
||||
} else if (x > rightThreshold) {
|
||||
currentZone = 'right';
|
||||
} else {
|
||||
currentZone = 'middle';
|
||||
}
|
||||
|
||||
if (timeSinceLastClick < this.DOUBLE_CLICK_INTERVAL_MS && this.lastClickZone === currentZone) {
|
||||
this.lastClickTime = now;
|
||||
this.lastClickZone = currentZone;
|
||||
|
||||
if (currentZone !== 'middle') {
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastClickTime = now;
|
||||
this.lastClickZone = currentZone;
|
||||
|
||||
setTimeout(() => {
|
||||
if (Date.now() - this.lastClickTime >= this.DOUBLE_CLICK_INTERVAL_MS) {
|
||||
this.processIframeClick(data);
|
||||
}
|
||||
}, this.DOUBLE_CLICK_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private processIframeClick(data: any): void {
|
||||
if (!this.longHoldTimeout) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isNavigating) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewRect = this.view.getBoundingClientRect();
|
||||
const x = data.clientX - viewRect.left;
|
||||
const width = viewRect.width;
|
||||
|
||||
const leftThreshold = width * this.LEFT_ZONE_PERCENT;
|
||||
const rightThreshold = width * this.RIGHT_ZONE_PERCENT;
|
||||
|
||||
if (x < leftThreshold) {
|
||||
this.isNavigating = true;
|
||||
this.prev();
|
||||
setTimeout(() => this.isNavigating = false, 300);
|
||||
} else if (x > rightThreshold) {
|
||||
this.isNavigating = true;
|
||||
this.next();
|
||||
setTimeout(() => this.isNavigating = false, 300);
|
||||
} else {
|
||||
this.eventSubject.next({type: 'middle-single-tap'});
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
export interface HeaderFooterVisibilityState {
|
||||
headerVisible: boolean;
|
||||
footerVisible: boolean;
|
||||
}
|
||||
|
||||
export class ReaderHeaderFooterVisibilityManager {
|
||||
private isPinned = false;
|
||||
private mouseY = 0;
|
||||
|
||||
private readonly HEADER_HEIGHT = 20;
|
||||
private readonly FOOTER_HEIGHT = 20;
|
||||
private readonly TRIGGER_ZONE = 20;
|
||||
|
||||
private headerVisible = false;
|
||||
private footerVisible = false;
|
||||
|
||||
private onStateChangeCallback?: (state: HeaderFooterVisibilityState) => void;
|
||||
|
||||
constructor(private windowHeight: number) {
|
||||
}
|
||||
|
||||
onStateChange(callback: (state: HeaderFooterVisibilityState) => void): void {
|
||||
this.onStateChangeCallback = callback;
|
||||
}
|
||||
|
||||
updateWindowHeight(height: number): void {
|
||||
this.windowHeight = height;
|
||||
}
|
||||
|
||||
handleMouseMove(mouseY: number): void {
|
||||
this.mouseY = mouseY;
|
||||
this.updateVisibility();
|
||||
}
|
||||
|
||||
handleMouseLeave(): void {
|
||||
if (!this.isPinned) {
|
||||
this.setHeaderVisible(false);
|
||||
this.setFooterVisible(false);
|
||||
this.notifyStateChange();
|
||||
}
|
||||
}
|
||||
|
||||
togglePinned(): void {
|
||||
this.isPinned = !this.isPinned;
|
||||
this.updateVisibility();
|
||||
}
|
||||
|
||||
getVisibilityState(): HeaderFooterVisibilityState {
|
||||
return {
|
||||
headerVisible: this.headerVisible,
|
||||
footerVisible: this.footerVisible
|
||||
};
|
||||
}
|
||||
|
||||
private updateVisibility(): void {
|
||||
if (
|
||||
this.mouseY <= this.TRIGGER_ZONE ||
|
||||
(this.mouseY <= this.HEADER_HEIGHT && this.headerVisible) ||
|
||||
this.isPinned
|
||||
) {
|
||||
this.setHeaderVisible(true);
|
||||
} else if (this.mouseY > this.HEADER_HEIGHT) {
|
||||
this.setHeaderVisible(this.isPinned);
|
||||
}
|
||||
|
||||
const footerTop = this.windowHeight - this.FOOTER_HEIGHT;
|
||||
if (
|
||||
this.mouseY >= this.windowHeight - this.TRIGGER_ZONE ||
|
||||
(this.mouseY >= footerTop && this.footerVisible) ||
|
||||
this.isPinned
|
||||
) {
|
||||
this.setFooterVisible(true);
|
||||
} else if (this.mouseY < footerTop) {
|
||||
this.setFooterVisible(this.isPinned);
|
||||
}
|
||||
|
||||
this.notifyStateChange();
|
||||
}
|
||||
|
||||
private setHeaderVisible(visible: boolean): void {
|
||||
this.headerVisible = visible;
|
||||
}
|
||||
|
||||
private setFooterVisible(visible: boolean): void {
|
||||
this.footerVisible = visible;
|
||||
}
|
||||
|
||||
private notifyStateChange(): void {
|
||||
if (this.onStateChangeCallback) {
|
||||
this.onStateChangeCallback(this.getVisibilityState());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
export interface PageInfo {
|
||||
percentCompleted: number;
|
||||
sectionTimeText: string;
|
||||
}
|
||||
|
||||
export interface ThemeInfo {
|
||||
fg: string;
|
||||
bg: string;
|
||||
}
|
||||
|
||||
export class ReaderHeaderFooterUtil {
|
||||
private static readonly DEFAULT_FONT_SIZE = '0.875rem';
|
||||
|
||||
static updateHeadersAndFooters(renderer: any, chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void {
|
||||
|
||||
if (!renderer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columnCount = renderer.heads?.length || 0;
|
||||
const isSingleColumn = columnCount === 1;
|
||||
|
||||
this.updateHeaders(renderer, chapterName, isSingleColumn, theme);
|
||||
this.updateFooters(renderer, pageInfo, isSingleColumn, theme);
|
||||
}
|
||||
|
||||
private static updateHeaders(renderer: any, chapterName: string, isSingleColumn: boolean, theme?: ThemeInfo): void {
|
||||
if (!renderer.heads || !Array.isArray(renderer.heads) || renderer.heads.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const headerStyle = this.buildStyle(theme);
|
||||
|
||||
renderer.heads.forEach((headElement: HTMLElement, index: number) => {
|
||||
if (headElement) {
|
||||
headElement.style.visibility = 'visible';
|
||||
const headerContent = this.createHeaderContent(chapterName, isSingleColumn, index, headerStyle);
|
||||
headElement.replaceChildren(headerContent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static updateFooters(renderer: any, pageInfo: PageInfo | undefined, isSingleColumn: boolean, theme?: ThemeInfo): void {
|
||||
if (!renderer.feet || !Array.isArray(renderer.feet) || renderer.feet.length === 0 || !pageInfo) {
|
||||
return;
|
||||
}
|
||||
|
||||
const footerStyle = this.buildStyle(theme);
|
||||
|
||||
renderer.feet.forEach((footElement: HTMLElement, index: number) => {
|
||||
if (footElement) {
|
||||
const footerContent = this.createFooterContent(pageInfo, isSingleColumn, index, renderer.feet.length, footerStyle);
|
||||
footElement.replaceChildren(footerContent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static buildStyle(theme?: ThemeInfo): string {
|
||||
const baseStyle = `width: 100%; display: flex; justify-content: space-between; align-items: center; font-size: ${this.DEFAULT_FONT_SIZE}; font-family: inherit;`;
|
||||
if (theme) {
|
||||
return `${baseStyle} color: ${theme.fg};`;
|
||||
}
|
||||
return baseStyle;
|
||||
}
|
||||
|
||||
private static createHeaderContent(chapterName: string, isSingleColumn: boolean, index: number, style: string): HTMLElement {
|
||||
const headerContent = document.createElement('div');
|
||||
headerContent.style.cssText = style;
|
||||
|
||||
if (isSingleColumn) {
|
||||
const spacer = document.createElement('span');
|
||||
const chapterSpan = document.createElement('span');
|
||||
chapterSpan.textContent = chapterName || '';
|
||||
chapterSpan.style.textAlign = 'right';
|
||||
headerContent.style.justifyContent = 'left';
|
||||
|
||||
headerContent.appendChild(spacer);
|
||||
headerContent.appendChild(chapterSpan);
|
||||
} else {
|
||||
if (index === 0) {
|
||||
const chapterSpan = document.createElement('span');
|
||||
chapterSpan.textContent = chapterName || '';
|
||||
chapterSpan.style.textAlign = 'left';
|
||||
headerContent.appendChild(chapterSpan);
|
||||
}
|
||||
}
|
||||
|
||||
return headerContent;
|
||||
}
|
||||
|
||||
private static createFooterContent(pageInfo: PageInfo, isSingleColumn: boolean, index: number, totalColumns: number, style: string): HTMLElement {
|
||||
const footerContent = document.createElement('div');
|
||||
footerContent.style.cssText = style;
|
||||
|
||||
const text = 'Time remaining in section: ' + (pageInfo.sectionTimeText ?? '0s');
|
||||
|
||||
if (isSingleColumn) {
|
||||
const timeSpan = document.createElement('span');
|
||||
timeSpan.textContent = text;
|
||||
timeSpan.style.textAlign = 'left';
|
||||
|
||||
const progressSpan = document.createElement('span');
|
||||
progressSpan.textContent = `${pageInfo.percentCompleted}%`;
|
||||
progressSpan.style.textAlign = 'right';
|
||||
|
||||
footerContent.appendChild(timeSpan);
|
||||
footerContent.appendChild(progressSpan);
|
||||
} else {
|
||||
if (index === 0) {
|
||||
const timeSpan = document.createElement('span');
|
||||
timeSpan.textContent = text;
|
||||
timeSpan.style.textAlign = 'left';
|
||||
footerContent.appendChild(timeSpan);
|
||||
|
||||
const spacer = document.createElement('span');
|
||||
footerContent.appendChild(spacer);
|
||||
} else if (index === totalColumns - 1) {
|
||||
const spacer = document.createElement('span');
|
||||
footerContent.appendChild(spacer);
|
||||
|
||||
const progressSpan = document.createElement('span');
|
||||
progressSpan.textContent = `${pageInfo.percentCompleted}%`;
|
||||
progressSpan.style.textAlign = 'right';
|
||||
footerContent.appendChild(progressSpan);
|
||||
}
|
||||
}
|
||||
|
||||
return footerContent;
|
||||
}
|
||||
}
|
||||
@@ -695,7 +695,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
|
||||
this.progressPercentage = Math.round(percentage * 1000) / 10;
|
||||
}
|
||||
|
||||
this.bookService.saveEpubProgress(this.epub.id, cfi, Math.round(percentage * 1000) / 10).subscribe();
|
||||
//this.bookService.saveEpubProgress(this.epub.id, cfi, '', Math.round(percentage * 1000) / 10).subscribe();
|
||||
|
||||
this.readingSessionService.updateProgress(
|
||||
location.start.cfi,
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {CustomFontService} from '../../../../shared/service/custom-font.service';
|
||||
import {CustomFont} from '../../../../shared/model/custom-font.model';
|
||||
import {Observable, forkJoin, of, from} from 'rxjs';
|
||||
import {map, switchMap, tap, catchError} from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class EpubCustomFontService {
|
||||
private customFontService = inject(CustomFontService);
|
||||
|
||||
private customFonts: CustomFont[] = [];
|
||||
private customFontBlobUrls = new Map<number, string>();
|
||||
|
||||
loadAndCacheFonts(): Observable<CustomFont[]> {
|
||||
return this.customFontService.getUserFonts().pipe(
|
||||
tap(fonts => this.customFonts = fonts),
|
||||
switchMap(fonts =>
|
||||
from(this.customFontService.loadAllFonts(fonts)).pipe(
|
||||
switchMap(() => this.cacheCustomFontsAsBlobs(fonts)),
|
||||
map(() => fonts)
|
||||
)
|
||||
),
|
||||
catchError(() => of([]))
|
||||
);
|
||||
}
|
||||
|
||||
private cacheCustomFontsAsBlobs(fonts: CustomFont[]): Observable<void> {
|
||||
if (fonts.length === 0) {
|
||||
return of(undefined);
|
||||
}
|
||||
|
||||
const requests = fonts.map(font =>
|
||||
this.cacheSingleFont(font).pipe(
|
||||
catchError(() => of(undefined))
|
||||
)
|
||||
);
|
||||
|
||||
return forkJoin(requests).pipe(map(() => undefined));
|
||||
}
|
||||
|
||||
private cacheSingleFont(font: CustomFont): Observable<void> {
|
||||
const fontUrl = this.customFontService.getFontUrl(font.id);
|
||||
const fontUrlWithToken = this.customFontService.appendToken(fontUrl);
|
||||
|
||||
return from(fetch(fontUrlWithToken)).pipe(
|
||||
switchMap(response => from(response.blob())),
|
||||
tap(blob => {
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
this.customFontBlobUrls.set(font.id, blobUrl);
|
||||
}),
|
||||
map(() => undefined)
|
||||
);
|
||||
}
|
||||
|
||||
getBlobUrl(fontId: number): string | undefined {
|
||||
return this.customFontBlobUrls.get(fontId);
|
||||
}
|
||||
|
||||
getCustomFonts(): CustomFont[] {
|
||||
return this.customFonts;
|
||||
}
|
||||
|
||||
getCustomFontById(fontId: number): CustomFont | undefined {
|
||||
return this.customFonts.find(f => f.id === fontId);
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
this.customFontBlobUrls.forEach(url => URL.revokeObjectURL(url));
|
||||
this.customFontBlobUrls.clear();
|
||||
}
|
||||
|
||||
sanitizeFontName(fontName: string): string {
|
||||
return fontName.replace(/\.(ttf|otf|woff|woff2)$/i, '').replace(/["'()]/g, '').replace(/\s+/g, '-');
|
||||
}
|
||||
|
||||
getFontFamilyForPreview(fontValue: string): string {
|
||||
if (fontValue.startsWith('custom:')) {
|
||||
const id = parseInt(fontValue.substring(7), 10);
|
||||
if (!isNaN(id)) {
|
||||
const customFont = this.getCustomFontById(id);
|
||||
if (customFont) {
|
||||
return `"${this.sanitizeFontName(customFont.fontName)}", sans-serif`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fontValue;
|
||||
}
|
||||
|
||||
generateCustomFontsStylesheet(): string {
|
||||
const customFonts = this.getCustomFonts();
|
||||
if (customFonts.length === 0) return '';
|
||||
|
||||
let css = '';
|
||||
customFonts.forEach(font => {
|
||||
const blobUrl = this.getBlobUrl(font.id);
|
||||
if (blobUrl) {
|
||||
const sanitizedName = this.sanitizeFontName(font.fontName);
|
||||
css += `
|
||||
@font-face {
|
||||
font-family: "${sanitizedName}";
|
||||
src: url("${blobUrl}") format("truetype");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
return css;
|
||||
}
|
||||
|
||||
injectCustomFontsStylesheet(renderer: any, document: Document): void {
|
||||
const css = this.generateCustomFontsStylesheet();
|
||||
if (css) {
|
||||
const styleEl = renderer.createElement('style');
|
||||
styleEl.textContent = css;
|
||||
renderer.appendChild(document.head, styleEl);
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -180,10 +180,12 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
background: var(--p-content-background);
|
||||
border-radius: 8px;
|
||||
background: rgba(220, 38, 38, 0.1);
|
||||
border: 1px solid rgba(220, 38, 38, 0.3);
|
||||
color: var(--p-red-400);
|
||||
max-width: 500px;
|
||||
margin: 0 1rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
@@ -191,21 +193,24 @@
|
||||
}
|
||||
|
||||
.pi {
|
||||
font-size: 1.5rem;
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 1.25rem;
|
||||
flex-shrink: 0;
|
||||
color: var(--p-red-300);
|
||||
}
|
||||
}
|
||||
|
||||
.access-denied-content {
|
||||
h3 {
|
||||
margin: 0 0 0.25rem 0;
|
||||
margin: 0 0 0.5rem 0;
|
||||
font-size: 1rem;
|
||||
color: var(--p-text-color);
|
||||
font-weight: 600;
|
||||
color: var(--p-red-300);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
color: var(--p-red-400);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-3
@@ -15,7 +15,13 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- EPUB Settings -->
|
||||
<div class="info-notice unsupported-formats-note" style="margin-bottom: 1rem;">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<div>
|
||||
<strong>Note:</strong> Writing metadata is <b>not supported</b> for FB2, AZW3, and MOBI formats.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<label class="setting-label">Write Metadata to EPUB</label>
|
||||
@@ -55,7 +61,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- CBX Settings -->
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<label class="setting-label">Write Metadata to CBX</label>
|
||||
@@ -95,7 +100,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- PDF Settings -->
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<label class="setting-label">Write Metadata to PDF</label>
|
||||
|
||||
+26
@@ -213,3 +213,29 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.info-notice.unsupported-formats-note {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--p-surface-900) 90%,
|
||||
var(--p-blue-600) 10%
|
||||
);
|
||||
border-left: 4px solid var(--p-blue-400);
|
||||
color: var(--p-text-color);
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
|
||||
.pi-info-circle {
|
||||
color: var(--p-blue-400);
|
||||
margin-top: 0.15rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
strong {
|
||||
color: var(--p-blue-300);
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -87,11 +87,11 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
|
||||
saveToOriginalFile: {
|
||||
epub: {
|
||||
enabled: persistenceSettings.saveToOriginalFile?.epub?.enabled ?? false,
|
||||
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.epub?.maxFileSizeInMb ?? 100
|
||||
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.epub?.maxFileSizeInMb ?? 250
|
||||
},
|
||||
pdf: {
|
||||
enabled: persistenceSettings.saveToOriginalFile?.pdf?.enabled ?? false,
|
||||
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.pdf?.maxFileSizeInMb ?? 100
|
||||
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.pdf?.maxFileSizeInMb ?? 250
|
||||
},
|
||||
cbx: {
|
||||
enabled: persistenceSettings.saveToOriginalFile?.cbx?.enabled ?? false,
|
||||
|
||||
+266
-102
@@ -1,125 +1,289 @@
|
||||
<div class="epub-preferences-container">
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Theme</label>
|
||||
<div class="theme-selector">
|
||||
@for (theme of themes; track theme) {
|
||||
<button
|
||||
type="button"
|
||||
class="theme-option"
|
||||
[class.selected]="selectedTheme === theme.key"
|
||||
[style.background-color]="theme.color"
|
||||
(click)="selectedTheme = theme.key"
|
||||
[attr.aria-label]="theme.name"
|
||||
[pTooltip]="theme.name"
|
||||
tooltipPosition="bottom">
|
||||
@if (selectedTheme === theme.key) {
|
||||
<i class="pi pi-check"></i>
|
||||
}
|
||||
</button>
|
||||
}
|
||||
|
||||
<div class="settings-group">
|
||||
<h3 class="group-title">Appearance</h3>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Theme</label>
|
||||
<div class="theme-selector">
|
||||
@for (theme of themes; track theme) {
|
||||
<button
|
||||
type="button"
|
||||
class="theme-option"
|
||||
[class.selected]="selectedTheme === theme.name"
|
||||
(click)="selectedTheme = theme.name"
|
||||
[attr.aria-label]="theme.label"
|
||||
[pTooltip]="theme.label"
|
||||
tooltipPosition="bottom">
|
||||
<span class="theme-colors">
|
||||
<span class="theme-color" [style.background-color]="theme.light.bg"></span>
|
||||
<span class="theme-color" [style.background-color]="theme.dark.bg"></span>
|
||||
</span>
|
||||
@if (selectedTheme === theme.name) {
|
||||
<i class="pi pi-check"></i>
|
||||
}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Select a color scheme to match your reading environment and comfort.
|
||||
</p>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Choose the visual theme for EPUB reading experience.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Font</label>
|
||||
<div class="button-group">
|
||||
@for (font of fonts; track font) {
|
||||
<button
|
||||
type="button"
|
||||
class="option-button font-button"
|
||||
[class.selected]="selectedFont === font.key"
|
||||
[class.separator]="font.key === 'separator'"
|
||||
[attr.data-font]="font.key"
|
||||
[disabled]="font.key === 'separator'"
|
||||
(click)="selectedFont = font.key"
|
||||
[pTooltip]="font.name"
|
||||
tooltipPosition="bottom">
|
||||
<span class="option-text"
|
||||
[style.font-family]="font.key && font.key.startsWith('custom:') ? getCustomFontName(font.key) : null">
|
||||
{{ font.displayName }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
|
||||
@if (!customFontsReady) {
|
||||
<p-skeleton width="3.5rem" height="2.5rem" borderRadius="6px"></p-skeleton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Select the font family for text display.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Flow</label>
|
||||
<div class="button-group">
|
||||
@for (flow of flowOptions; track flow) {
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Dark Mode</label>
|
||||
<div class="button-group">
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="selectedFlow === flow.key"
|
||||
(click)="selectedFlow = flow.key">
|
||||
<i [class]="flow.icon"></i>
|
||||
<span class="option-text">{{ flow.name }}</span>
|
||||
[class.selected]="!isDark"
|
||||
(click)="isDark = false">
|
||||
<i class="pi pi-sun"></i>
|
||||
<span class="option-text">Light</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Configure text flow and reading direction.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Page Spread</label>
|
||||
<div class="button-group">
|
||||
@for (spread of spreadOptions; track spread) {
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="selectedSpread === spread.key"
|
||||
(click)="selectedSpread = spread.key">
|
||||
<i [class]="spread.icon"></i>
|
||||
<span class="option-text">{{ spread.name }}</span>
|
||||
[class.selected]="isDark"
|
||||
(click)="isDark = true">
|
||||
<i class="pi pi-moon"></i>
|
||||
<span class="option-text">Dark</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Switch between light and dark backgrounds for day or night reading.
|
||||
</p>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Choose between single page or double page spread view.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Font Size</label>
|
||||
<div class="font-size-controls">
|
||||
<p-button icon="pi pi-minus" size="small" rounded (click)="decreaseFontSize()"></p-button>
|
||||
<span class="font-size-value">{{ fontSize }}%</span>
|
||||
<p-button icon="pi pi-plus" size="small" rounded (click)="increaseFontSize()"></p-button>
|
||||
<div class="settings-group">
|
||||
<h3 class="group-title">Typography</h3>
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Font Family</label>
|
||||
<div class="button-group">
|
||||
@for (font of fonts; track font) {
|
||||
<button
|
||||
type="button"
|
||||
class="option-button font-button"
|
||||
[class.selected]="selectedFont === font.key"
|
||||
[class.separator]="font.key === 'separator'"
|
||||
[attr.data-font]="font.key"
|
||||
[disabled]="font.key === 'separator'"
|
||||
(click)="selectedFont = font.key"
|
||||
[pTooltip]="font.name"
|
||||
tooltipPosition="bottom">
|
||||
<span class="option-text" [style.font-family]="font.key && font.key.startsWith('custom:') ? getCustomFontName(font.key) : null">
|
||||
{{ font.displayName }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
|
||||
@if (!customFontsReady) {
|
||||
<p-skeleton width="3.5rem" height="2.5rem" borderRadius="6px"></p-skeleton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Choose a typeface that best suits your reading preference.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Font Size</label>
|
||||
<div class="font-size-controls">
|
||||
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseFontSize()"></p-button>
|
||||
<span class="font-size-value">{{ fontSize }}pt</span>
|
||||
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseFontSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Increase or decrease text size in points for optimal readability.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Line Height</label>
|
||||
<div class="font-size-controls">
|
||||
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseLineHeight()"></p-button>
|
||||
<span class="font-size-value">{{ lineHeight.toFixed(1) }}</span>
|
||||
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseLineHeight()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Adjust vertical spacing between lines for better legibility.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Text Justification</label>
|
||||
<div class="button-group">
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="!justify"
|
||||
(click)="justify = false">
|
||||
<i class="pi pi-align-left"></i>
|
||||
<span class="option-text">Left</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="justify"
|
||||
(click)="justify = true">
|
||||
<i class="pi pi-align-justify"></i>
|
||||
<span class="option-text">Justified</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Align text to the left or justify it for a clean edge on both sides.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Hyphenation</label>
|
||||
<div class="button-group">
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="!hyphenate"
|
||||
(click)="hyphenate = false">
|
||||
<i class="pi pi-times"></i>
|
||||
<span class="option-text">Off</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="hyphenate"
|
||||
(click)="hyphenate = true">
|
||||
<i class="pi pi-check"></i>
|
||||
<span class="option-text">On</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Enable to break long words at line ends for a smoother text flow.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<h3 class="group-title">Layout</h3>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Flow</label>
|
||||
<div class="button-group">
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="flow === 'paginated'"
|
||||
(click)="flow = 'paginated'">
|
||||
<i class="pi pi-clone"></i>
|
||||
<span class="option-text">Paginated</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="flow === 'scrolled'"
|
||||
(click)="flow = 'scrolled'">
|
||||
<i class="pi pi-arrows-v"></i>
|
||||
<span class="option-text">Scrolled</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Choose between paginated (page-by-page) or continuous scrolling flow.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Max Columns</label>
|
||||
<div class="font-size-controls">
|
||||
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="maxColumnCount = maxColumnCount > 1 ? maxColumnCount - 1 : 1"></p-button>
|
||||
<span class="font-size-value">{{ maxColumnCount }}</span>
|
||||
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="maxColumnCount = maxColumnCount < 4 ? maxColumnCount + 1 : 4"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Set how many columns the text is split into on wide screens.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Column Gap</label>
|
||||
<div class="font-size-controls">
|
||||
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseGap()"></p-button>
|
||||
<span class="font-size-value">{{ gap }}px</span>
|
||||
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseGap()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Control the space between columns for a balanced layout.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Max Width</label>
|
||||
<div class="font-size-controls">
|
||||
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseMaxInlineSize()"></p-button>
|
||||
<span class="font-size-value">{{ maxInlineSize }}px</span>
|
||||
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseMaxInlineSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Limit the maximum width of the reading area for easier line tracking.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Max Height</label>
|
||||
<div class="font-size-controls">
|
||||
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseMaxBlockSize()"></p-button>
|
||||
<span class="font-size-value">{{ maxBlockSize }}px</span>
|
||||
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseMaxBlockSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Limit the maximum height of the reading area to fit your screen.
|
||||
</p>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Adjust the text size for comfortable reading.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+73
-16
@@ -1,7 +1,25 @@
|
||||
.epub-preferences-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.settings-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
padding: 1.5rem;
|
||||
border-radius: 0.75rem;
|
||||
border: 1px solid color-mix(in srgb, var(--text-color) 10%, transparent);
|
||||
|
||||
.group-title {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.5rem 0;
|
||||
padding-bottom: 0.75rem;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--text-color) 10%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.setting-item {
|
||||
@@ -80,7 +98,7 @@
|
||||
.font-size-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
gap: 0.5rem;
|
||||
|
||||
.font-size-value {
|
||||
min-width: 3rem;
|
||||
@@ -96,32 +114,70 @@
|
||||
flex-wrap: wrap;
|
||||
|
||||
.theme-option {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1.5px solid transparent;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
background: color-mix(in srgb, var(--text-color) 5%, transparent);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 48px;
|
||||
|
||||
.theme-colors {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
border-radius: 0.5rem;
|
||||
overflow: hidden;
|
||||
border: 2px solid color-mix(in srgb, var(--text-color) 20%, transparent);
|
||||
box-sizing: border-box;
|
||||
width: 72px;
|
||||
height: 36px;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.theme-color {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
display: inline-block;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
i {
|
||||
color: white;
|
||||
font-size: 0.875rem;
|
||||
font-weight: bold;
|
||||
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
font-size: 0.75rem;
|
||||
color: var(--primary-color);
|
||||
margin-left: 0;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
|
||||
.theme-colors {
|
||||
border-color: color-mix(in srgb, var(--primary-color) 40%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
&.selected {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 25%, transparent);
|
||||
.theme-colors {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 15%, transparent);
|
||||
}
|
||||
color: var(--primary-color);
|
||||
background: color-mix(in srgb, var(--primary-color) 10%, transparent);
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,3 +275,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+150
-91
@@ -9,6 +9,7 @@ import {CustomFont} from '../../../../shared/model/custom-font.model';
|
||||
import {skip, Subject, takeUntil} from 'rxjs';
|
||||
import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util';
|
||||
import {Skeleton} from 'primeng/skeleton';
|
||||
import {themes} from '../../../readers/ebook-reader/services/reader-themes';
|
||||
|
||||
@Component({
|
||||
selector: 'app-epub-reader-preferences-component',
|
||||
@@ -40,33 +41,7 @@ export class EpubReaderPreferencesComponent implements OnInit, OnDestroy {
|
||||
{name: 'Monospace', displayName: 'Monospace', key: 'monospace'}
|
||||
];
|
||||
|
||||
readonly flowOptions = [
|
||||
{name: 'Paginated', key: 'paginated', icon: 'pi pi-book'},
|
||||
{name: 'Scrolled', key: 'scrolled', icon: 'pi pi-sort-alt'}
|
||||
];
|
||||
|
||||
readonly spreadOptions = [
|
||||
{name: 'Single', key: 'single', icon: 'pi pi-file'},
|
||||
{name: 'Double', key: 'double', icon: 'pi pi-copy'}
|
||||
];
|
||||
|
||||
readonly themes = [
|
||||
{name: 'White', key: 'white', color: '#FFFFFF'},
|
||||
{name: 'Black', key: 'black', color: '#1A1A1A'},
|
||||
{name: 'Grey', key: 'grey', color: '#4B5563'},
|
||||
{name: 'Sepia', key: 'sepia', color: '#F4ECD8'},
|
||||
{name: 'Green', key: 'green', color: '#D1FAE5'},
|
||||
{name: 'Lavender', key: 'lavender', color: '#E9D5FF'},
|
||||
{name: 'Cream', key: 'cream', color: '#FEF3C7'},
|
||||
{name: 'Light Blue', key: 'light-blue', color: '#DBEAFE'},
|
||||
{name: 'Peach', key: 'peach', color: '#FECACA'},
|
||||
{name: 'Mint', key: 'mint', color: '#A7F3D0'},
|
||||
{name: 'Dark Slate', key: 'dark-slate', color: '#1E293B'},
|
||||
{name: 'Dark Olive', key: 'dark-olive', color: '#3F3F2C'},
|
||||
{name: 'Dark Purple', key: 'dark-purple', color: '#3B2F4A'},
|
||||
{name: 'Dark Teal', key: 'dark-teal', color: '#0F3D3E'},
|
||||
{name: 'Dark Brown', key: 'dark-brown', color: '#3E2723'}
|
||||
];
|
||||
readonly themes = themes;
|
||||
|
||||
customFontsReady = false;
|
||||
|
||||
@@ -129,12 +104,13 @@ export class EpubReaderPreferencesComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private isCurrentlySelectedFontDeleted(newFonts: CustomFont[]): boolean {
|
||||
const customFontId = this.userSettings.epubReaderSetting.customFontId;
|
||||
if (!customFontId) {
|
||||
const fontFamily = this.userSettings.ebookReaderSetting.fontFamily;
|
||||
if (!fontFamily || !fontFamily.startsWith('custom:')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const fontStillExists = newFonts.some(font => font.id === customFontId);
|
||||
const fontId = fontFamily.split(':')[1];
|
||||
const fontStillExists = newFonts.some(font => font.id === parseInt(fontId, 10));
|
||||
return !fontStillExists;
|
||||
}
|
||||
|
||||
@@ -144,93 +120,176 @@ export class EpubReaderPreferencesComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
get selectedTheme(): string | null {
|
||||
return this.userSettings.epubReaderSetting.theme;
|
||||
return this.userSettings.ebookReaderSetting.theme;
|
||||
}
|
||||
|
||||
set selectedTheme(value: string | null) {
|
||||
if (typeof value === "string") {
|
||||
this.userSettings.epubReaderSetting.theme = value;
|
||||
this.userSettings.ebookReaderSetting.theme = value;
|
||||
}
|
||||
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'theme'], value);
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'theme'], value);
|
||||
}
|
||||
|
||||
get selectedFont(): string | null {
|
||||
// If customFontId is set, return the custom font key
|
||||
if (this.userSettings.epubReaderSetting.customFontId) {
|
||||
return `custom:${this.userSettings.epubReaderSetting.customFontId}`;
|
||||
}
|
||||
return this.userSettings.epubReaderSetting.font;
|
||||
return this.userSettings.ebookReaderSetting.fontFamily;
|
||||
}
|
||||
|
||||
set selectedFont(value: string | null) {
|
||||
// Handle custom fonts
|
||||
if (value && value.startsWith('custom:')) {
|
||||
const fontIdStr = value.split(':')[1];
|
||||
const fontId = parseInt(fontIdStr, 10);
|
||||
|
||||
if (isNaN(fontId)) {
|
||||
console.error('Invalid custom font ID:', value);
|
||||
return;
|
||||
}
|
||||
|
||||
// Update both fields in local state
|
||||
this.userSettings.epubReaderSetting.customFontId = fontId;
|
||||
this.userSettings.epubReaderSetting.font = value;
|
||||
if (typeof value === "string") {
|
||||
this.userSettings.ebookReaderSetting.fontFamily = value;
|
||||
} else {
|
||||
// Clear customFontId and set font in local state
|
||||
this.userSettings.epubReaderSetting.customFontId = null;
|
||||
if (typeof value === "string") {
|
||||
this.userSettings.epubReaderSetting.font = value;
|
||||
} else {
|
||||
// value is null - set to default font
|
||||
this.userSettings.epubReaderSetting.font = null as any;
|
||||
}
|
||||
this.userSettings.ebookReaderSetting.fontFamily = null as any;
|
||||
}
|
||||
|
||||
// Single API call with entire epubReaderSetting object
|
||||
this.readerPreferencesService.updatePreference(['epubReaderSetting'], this.userSettings.epubReaderSetting);
|
||||
}
|
||||
|
||||
get selectedFlow(): string | null {
|
||||
return this.userSettings.epubReaderSetting.flow;
|
||||
}
|
||||
|
||||
set selectedFlow(value: string | null) {
|
||||
if (typeof value === "string") {
|
||||
this.userSettings.epubReaderSetting.flow = value;
|
||||
}
|
||||
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'flow'], value);
|
||||
}
|
||||
|
||||
get selectedSpread(): string | null {
|
||||
return this.userSettings.epubReaderSetting.spread;
|
||||
}
|
||||
|
||||
set selectedSpread(value: string | null) {
|
||||
if (typeof value === "string") {
|
||||
this.userSettings.epubReaderSetting.spread = value;
|
||||
}
|
||||
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'spread'], value);
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontFamily'], value);
|
||||
}
|
||||
|
||||
get fontSize(): number {
|
||||
return this.userSettings.epubReaderSetting.fontSize;
|
||||
return this.userSettings.ebookReaderSetting.fontSize;
|
||||
}
|
||||
|
||||
set fontSize(value: number) {
|
||||
this.userSettings.epubReaderSetting.fontSize = value;
|
||||
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'fontSize'], value);
|
||||
this.userSettings.ebookReaderSetting.fontSize = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontSize'], value);
|
||||
}
|
||||
|
||||
get lineHeight(): number {
|
||||
return this.userSettings.ebookReaderSetting.lineHeight;
|
||||
}
|
||||
|
||||
set lineHeight(value: number) {
|
||||
this.userSettings.ebookReaderSetting.lineHeight = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'lineHeight'], value);
|
||||
}
|
||||
|
||||
get justify(): boolean {
|
||||
return this.userSettings.ebookReaderSetting.justify;
|
||||
}
|
||||
|
||||
set justify(value: boolean) {
|
||||
this.userSettings.ebookReaderSetting.justify = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'justify'], value);
|
||||
}
|
||||
|
||||
get hyphenate(): boolean {
|
||||
return this.userSettings.ebookReaderSetting.hyphenate;
|
||||
}
|
||||
|
||||
set hyphenate(value: boolean) {
|
||||
this.userSettings.ebookReaderSetting.hyphenate = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'hyphenate'], value);
|
||||
}
|
||||
|
||||
get maxColumnCount(): number {
|
||||
return this.userSettings.ebookReaderSetting.maxColumnCount;
|
||||
}
|
||||
|
||||
set maxColumnCount(value: number) {
|
||||
this.userSettings.ebookReaderSetting.maxColumnCount = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxColumnCount'], value);
|
||||
}
|
||||
|
||||
get gap(): number {
|
||||
return this.userSettings.ebookReaderSetting.gap;
|
||||
}
|
||||
|
||||
set gap(value: number) {
|
||||
this.userSettings.ebookReaderSetting.gap = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'gap'], value);
|
||||
}
|
||||
|
||||
get maxInlineSize(): number {
|
||||
return this.userSettings.ebookReaderSetting.maxInlineSize;
|
||||
}
|
||||
|
||||
set maxInlineSize(value: number) {
|
||||
this.userSettings.ebookReaderSetting.maxInlineSize = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxInlineSize'], value);
|
||||
}
|
||||
|
||||
get maxBlockSize(): number {
|
||||
return this.userSettings.ebookReaderSetting.maxBlockSize;
|
||||
}
|
||||
|
||||
set maxBlockSize(value: number) {
|
||||
this.userSettings.ebookReaderSetting.maxBlockSize = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxBlockSize'], value);
|
||||
}
|
||||
|
||||
get isDark(): boolean {
|
||||
return this.userSettings.ebookReaderSetting.isDark;
|
||||
}
|
||||
|
||||
set isDark(value: boolean) {
|
||||
this.userSettings.ebookReaderSetting.isDark = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'isDark'], value);
|
||||
}
|
||||
|
||||
get flow(): 'paginated' | 'scrolled' {
|
||||
return this.userSettings.ebookReaderSetting.flow;
|
||||
}
|
||||
|
||||
set flow(value: 'paginated' | 'scrolled') {
|
||||
this.userSettings.ebookReaderSetting.flow = value;
|
||||
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'flow'], value);
|
||||
}
|
||||
|
||||
increaseFontSize() {
|
||||
if (this.fontSize < 250) {
|
||||
this.fontSize += 10;
|
||||
if (this.fontSize < 72) {
|
||||
this.fontSize += 1;
|
||||
}
|
||||
}
|
||||
|
||||
decreaseFontSize() {
|
||||
if (this.fontSize > 50) {
|
||||
this.fontSize -= 10;
|
||||
if (this.fontSize > 8) {
|
||||
this.fontSize -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
increaseLineHeight() {
|
||||
if (this.lineHeight < 3) {
|
||||
this.lineHeight += 0.1;
|
||||
}
|
||||
}
|
||||
|
||||
decreaseLineHeight() {
|
||||
if (this.lineHeight > 1) {
|
||||
this.lineHeight -= 0.1;
|
||||
}
|
||||
}
|
||||
|
||||
increaseGap() {
|
||||
if (this.gap < 100) {
|
||||
this.gap += 5;
|
||||
}
|
||||
}
|
||||
|
||||
decreaseGap() {
|
||||
if (this.gap > 0) {
|
||||
this.gap -= 5;
|
||||
}
|
||||
}
|
||||
|
||||
increaseMaxInlineSize() {
|
||||
if (this.maxInlineSize < 2000) {
|
||||
this.maxInlineSize += 50;
|
||||
}
|
||||
}
|
||||
|
||||
decreaseMaxInlineSize() {
|
||||
if (this.maxInlineSize > 400) {
|
||||
this.maxInlineSize -= 50;
|
||||
}
|
||||
}
|
||||
|
||||
increaseMaxBlockSize() {
|
||||
if (this.maxBlockSize < 2000) {
|
||||
this.maxBlockSize += 50;
|
||||
}
|
||||
}
|
||||
|
||||
decreaseMaxBlockSize() {
|
||||
if (this.maxBlockSize > 400) {
|
||||
this.maxBlockSize -= 50;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-27
@@ -5,7 +5,7 @@
|
||||
Reader Preferences
|
||||
</h2>
|
||||
<p class="settings-description">
|
||||
Configure reader settings scope and customize reading experience for different book formats including PDF, EPUB, and CBX files.
|
||||
Configure reading experience settings for your library. Set default preferences that serve as overrides for individual books, or allow each book to maintain its own custom settings for PDF, EPUB, FB2, MOBI, AZW3, and CBX formats.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -14,10 +14,10 @@
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-cog"></i>
|
||||
Reader Settings Scope
|
||||
Settings Application Mode
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Select whether to apply the same reader settings (font, theme, spread, zoom, etc.) globally for all books or individually per book.
|
||||
Control how default settings are applied. Select "Default Override" to apply your configured defaults to all books of the same format, overriding individual book preferences. Choose "Book-Specific" to let each book retain its own custom reading settings.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -32,17 +32,15 @@
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="selectedPdfScope === item.key"
|
||||
(click)="selectedPdfScope = item.key; onPdfScopeChange()"
|
||||
[pTooltip]="item.name"
|
||||
tooltipPosition="bottom">
|
||||
(click)="selectedPdfScope = item.key; onPdfScopeChange()">
|
||||
<i [class]="item.icon"></i>
|
||||
<span class="option-text">{{ item.name }}</span>
|
||||
<span class="option-text">{{ item.key === 'Global' ? 'Default Override' : 'Book-Specific' }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Choose how PDF reader settings are applied across your library.
|
||||
Choose whether default zoom, layout, and navigation settings override individual PDF preferences or if each document maintains its own settings.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -50,24 +48,22 @@
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">EPUB Reader Settings</label>
|
||||
<label class="setting-label">eBook Reader Settings</label>
|
||||
<div class="button-group">
|
||||
@for (item of scopeOptions; track item) {
|
||||
<button
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="selectedEpubScope === item.key"
|
||||
(click)="selectedEpubScope = item.key; onEpubScopeChange()"
|
||||
[pTooltip]="item.name"
|
||||
tooltipPosition="bottom">
|
||||
(click)="selectedEpubScope = item.key; onEpubScopeChange()">
|
||||
<i [class]="item.icon"></i>
|
||||
<span class="option-text">{{ item.name }}</span>
|
||||
<span class="option-text">{{ item.key === 'Global' ? 'Default Override' : 'Book-Specific' }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Choose how EPUB reader settings are applied across your library.
|
||||
Choose whether default font, theme, and layout settings override individual eBook preferences (EPUB, FB2, MOBI, AZW3) or if each book maintains its own settings.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -82,17 +78,15 @@
|
||||
type="button"
|
||||
class="option-button"
|
||||
[class.selected]="selectedCbxScope === item.key"
|
||||
(click)="selectedCbxScope = item.key; onCbxScopeChange()"
|
||||
[pTooltip]="item.name"
|
||||
tooltipPosition="bottom">
|
||||
(click)="selectedCbxScope = item.key; onCbxScopeChange()">
|
||||
<i [class]="item.icon"></i>
|
||||
<span class="option-text">{{ item.name }}</span>
|
||||
<span class="option-text">{{ item.key === 'Global' ? 'Default Override' : 'Book-Specific' }}</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Choose how CBX (comic book) reader settings are applied across your library.
|
||||
Choose whether default layout, direction, and scaling settings override individual comic book preferences (CBZ, CBR, CB7) or if each file maintains its own settings.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -103,10 +97,10 @@
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-book"></i>
|
||||
EPUB Preferences: Global
|
||||
eBook Reader: Default Settings
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Set default reading options that will apply to all EPUB books in your library, including font, theme, text flow, and layout preferences.
|
||||
Set default preferences for eBook formats (EPUB, FB2, MOBI, AZW3). When "Default Override" mode is active, these settings will override individual book preferences. Configure typography, themes, text flow, and layout options.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -121,10 +115,10 @@
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-file-pdf"></i>
|
||||
PDF Preferences: Global
|
||||
PDF Reader: Default Settings
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Set default reading options that apply to all PDF books in your library, including zoom level, page layout, and navigation behavior.
|
||||
Set default preferences for PDF documents. When "Default Override" mode is active, these settings will override individual document preferences. Configure zoom levels, display modes, scroll behavior, and navigation.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -139,10 +133,10 @@
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-images"></i>
|
||||
CBX Preferences: Global
|
||||
Comic Book Reader: Default Settings
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Configure default reading settings for all comic books in your library, including page layout, reading direction, and image scaling.
|
||||
Set default preferences for comic book archives (CBZ, CBR, CB7). When "Default Override" mode is active, these settings will override individual file preferences. Configure page layout, reading direction, and image rendering.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -158,10 +152,10 @@
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-palette"></i>
|
||||
Custom Fonts Management
|
||||
Custom Font Library
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Upload and manage up to 10 custom fonts for a personalized reading experience in the EPUB reader. Each font can then be selected in the EPUB reader settings.
|
||||
Personalize your reading experience by uploading custom fonts to use with eBook formats (EPUB, FB2, MOBI, AZW3). Upload up to 10 custom font files that will be available for selection in the eBook reader settings.
|
||||
</p>
|
||||
</div>
|
||||
<div class="settings-card">
|
||||
|
||||
+15
-1
@@ -44,6 +44,20 @@ const mockUser: User = {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
ebookReaderSetting: {
|
||||
lineHeight: 1,
|
||||
justify: false,
|
||||
hyphenate: false,
|
||||
maxColumnCount: 1,
|
||||
gap: 0,
|
||||
fontSize: 1,
|
||||
theme: '',
|
||||
maxInlineSize: 0,
|
||||
maxBlockSize: 0,
|
||||
fontFamily: '',
|
||||
isDark: false,
|
||||
flow: 'paginated'
|
||||
},
|
||||
cbxReaderSetting: {
|
||||
pageSpread: CbxPageSpread.EVEN,
|
||||
pageViewMode: CbxPageViewMode.SINGLE_PAGE,
|
||||
@@ -61,7 +75,7 @@ const mockUser: User = {
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {
|
||||
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false},
|
||||
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false, overlayBookType: false},
|
||||
overrides: []
|
||||
},
|
||||
koReaderEnabled: false,
|
||||
|
||||
@@ -1,956 +0,0 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {of, throwError} from 'rxjs';
|
||||
|
||||
import {
|
||||
CbxFitMode,
|
||||
CbxPageSpread,
|
||||
CbxPageViewMode,
|
||||
PdfPageSpread,
|
||||
PdfPageViewMode,
|
||||
User,
|
||||
UserService,
|
||||
UserUpdateRequest
|
||||
} from './user.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
describe('UserService', () => {
|
||||
let service: UserService;
|
||||
let httpClientMock: any;
|
||||
let authServiceMock: any;
|
||||
|
||||
const mockUser: User = {
|
||||
id: 1,
|
||||
username: 'testuser',
|
||||
name: 'Test User',
|
||||
email: 'test@example.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: true,
|
||||
canUpload: true,
|
||||
canDownload: true,
|
||||
canEmailBook: true,
|
||||
canDeleteBook: true,
|
||||
canEditMetadata: true,
|
||||
canManageLibrary: true,
|
||||
canManageMetadataConfig: true,
|
||||
canSyncKoReader: true,
|
||||
canSyncKobo: true,
|
||||
canAccessOpds: true,
|
||||
canAccessBookdrop: true,
|
||||
canAccessLibraryStats: true,
|
||||
canAccessUserStats: true,
|
||||
canAccessTaskManager: true,
|
||||
canManageEmailConfig: true,
|
||||
canManageGlobalPreferences: true,
|
||||
canManageIcons: true,
|
||||
canManageFonts: true,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: true,
|
||||
canBulkCustomFetchMetadata: true,
|
||||
canBulkEditMetadata: true,
|
||||
canBulkRegenerateCover: true,
|
||||
canMoveOrganizeFiles: true,
|
||||
canBulkLockUnlockMetadata: true
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {
|
||||
pageSpread: CbxPageSpread.EVEN,
|
||||
pageViewMode: CbxPageViewMode.SINGLE_PAGE,
|
||||
fitMode: CbxFitMode.ACTUAL_SIZE
|
||||
},
|
||||
newPdfReaderSetting: {
|
||||
pageSpread: PdfPageSpread.EVEN,
|
||||
pageViewMode: PdfPageViewMode.SINGLE_PAGE
|
||||
},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and',
|
||||
filterSortingMode: 'alphabetical',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {
|
||||
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false},
|
||||
overrides: []
|
||||
},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
|
||||
authServiceMock = {
|
||||
token$: of('token')
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
UserService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: AuthService, useValue: authServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(UserService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should initialize with default state', () => {
|
||||
expect(service.userStateSubject.value).toEqual({
|
||||
user: null,
|
||||
loaded: false,
|
||||
error: null
|
||||
});
|
||||
});
|
||||
|
||||
it('should set initial user', () => {
|
||||
service.setInitialUser(mockUser);
|
||||
expect(service.userStateSubject.value.user).toEqual(mockUser);
|
||||
expect(service.userStateSubject.value.loaded).toBe(true);
|
||||
});
|
||||
|
||||
it('should get current user', () => {
|
||||
service.setInitialUser(mockUser);
|
||||
expect(service.getCurrentUser()).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it('should fetch myself and update state', () => {
|
||||
httpClientMock.get.mockReturnValue(of(mockUser));
|
||||
service['fetchMyself']().subscribe(user => {
|
||||
expect(user).toEqual(mockUser);
|
||||
expect(service.userStateSubject.value.user).toEqual(mockUser);
|
||||
expect(service.userStateSubject.value.loaded).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle fetch myself error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service['fetchMyself']().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(service.userStateSubject.value.error).toBe('fail');
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should get myself via getMyself()', () => {
|
||||
httpClientMock.get.mockReturnValue(of(mockUser));
|
||||
service.getMyself().subscribe(user => {
|
||||
expect(user).toEqual(mockUser);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/me'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should create user', () => {
|
||||
httpClientMock.post.mockReturnValue(of(void 0));
|
||||
const {id, ...userData} = mockUser;
|
||||
service.createUser(userData).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.post).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should get users', () => {
|
||||
httpClientMock.get.mockReturnValue(of([mockUser]));
|
||||
service.getUsers().subscribe(users => {
|
||||
expect(users).toEqual([mockUser]);
|
||||
expect(httpClientMock.get).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should update user', () => {
|
||||
httpClientMock.put.mockReturnValue(of(mockUser));
|
||||
const update: UserUpdateRequest = {name: 'New Name'};
|
||||
service.updateUser(1, update).subscribe(user => {
|
||||
expect(user).toEqual(mockUser);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), update);
|
||||
});
|
||||
});
|
||||
|
||||
it('should delete user', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
service.deleteUser(1).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should change user password', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.changeUserPassword(1, 'newpass').subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-user-password'), {userId: 1, newPassword: 'newpass'});
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle change user password error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'bad'}})));
|
||||
service.changeUserPassword(1, 'badpass').subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('bad');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should change password', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.changePassword('old', 'new').subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-password'), {currentPassword: 'old', newPassword: 'new'});
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle change password error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||
service.changePassword('old', 'bad').subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should update user setting and update state', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.setInitialUser(mockUser);
|
||||
service.updateUserSetting(1, 'koReaderEnabled', true);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1/settings'), {key: 'koReaderEnabled', value: true}, expect.anything());
|
||||
expect(service.userStateSubject.value.user?.userSettings.koReaderEnabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UserService - API Contract Tests', () => {
|
||||
let service: UserService;
|
||||
let httpClientMock: any;
|
||||
let authServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
|
||||
authServiceMock = {
|
||||
token$: of('token')
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
UserService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: AuthService, useValue: authServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(UserService));
|
||||
});
|
||||
|
||||
describe('User interface contract', () => {
|
||||
it('should validate all required User fields exist', () => {
|
||||
const requiredFields: (keyof User)[] = [
|
||||
'id', 'username', 'name', 'email', 'assignedLibraries', 'permissions', 'userSettings'
|
||||
];
|
||||
|
||||
const mockResponse: User = {
|
||||
id: 1,
|
||||
username: 'test',
|
||||
name: 'Test',
|
||||
email: 'test@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and',
|
||||
filterSortingMode: 'alphabetical',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||
|
||||
service.getMyself().subscribe(user => {
|
||||
requiredFields.forEach(field => {
|
||||
expect(user).toHaveProperty(field);
|
||||
expect(user[field]).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should validate all required Permission fields exist', () => {
|
||||
const requiredPermissions = [
|
||||
'admin', 'canUpload', 'canDownload', 'canEmailBook', 'canDeleteBook',
|
||||
'canEditMetadata', 'canManageLibrary', 'canManageMetadataConfig',
|
||||
'canSyncKoReader', 'canSyncKobo', 'canAccessOpds', 'canAccessBookdrop',
|
||||
'canAccessLibraryStats', 'canAccessUserStats', 'canAccessTaskManager',
|
||||
'canManageEmailConfig', 'canManageGlobalPreferences', 'canManageIcons',
|
||||
'canManageFonts', // <-- Added test for canManageFonts
|
||||
'demoUser', 'canBulkAutoFetchMetadata', 'canBulkCustomFetchMetadata',
|
||||
'canBulkEditMetadata', 'canBulkRegenerateCover', 'canMoveOrganizeFiles',
|
||||
'canBulkLockUnlockMetadata'
|
||||
];
|
||||
|
||||
const mockResponse: User = {
|
||||
id: 1,
|
||||
username: 'test',
|
||||
name: 'Test',
|
||||
email: 'test@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: true,
|
||||
canUpload: true,
|
||||
canDownload: true,
|
||||
canEmailBook: true,
|
||||
canDeleteBook: true,
|
||||
canEditMetadata: true,
|
||||
canManageLibrary: true,
|
||||
canManageMetadataConfig: true,
|
||||
canSyncKoReader: true,
|
||||
canSyncKobo: true,
|
||||
canAccessOpds: true,
|
||||
canAccessBookdrop: true,
|
||||
canAccessLibraryStats: true,
|
||||
canAccessUserStats: true,
|
||||
canAccessTaskManager: true,
|
||||
canManageEmailConfig: true,
|
||||
canManageGlobalPreferences: true,
|
||||
canManageIcons: true,
|
||||
canManageFonts: true, // <-- Added to mock
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: true,
|
||||
canBulkCustomFetchMetadata: true,
|
||||
canBulkEditMetadata: true,
|
||||
canBulkRegenerateCover: true,
|
||||
canMoveOrganizeFiles: true,
|
||||
canBulkLockUnlockMetadata: true
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and',
|
||||
filterSortingMode: 'alphabetical',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||
|
||||
service.getMyself().subscribe(user => {
|
||||
requiredPermissions.forEach(permission => {
|
||||
expect(user.permissions).toHaveProperty(permission);
|
||||
expect(typeof user.permissions[permission as keyof typeof user.permissions]).toBe('boolean');
|
||||
});
|
||||
// Explicit test for canManageFonts
|
||||
expect(user.permissions.canManageFonts).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should validate all required UserSettings fields exist', () => {
|
||||
const requiredSettings = [
|
||||
'perBookSetting', 'pdfReaderSetting', 'epubReaderSetting', 'cbxReaderSetting',
|
||||
'newPdfReaderSetting', 'sidebarLibrarySorting', 'sidebarShelfSorting',
|
||||
'sidebarMagicShelfSorting', 'filterMode', 'filterSortingMode',
|
||||
'metadataCenterViewMode', 'enableSeriesView', 'entityViewPreferences', 'koReaderEnabled'
|
||||
];
|
||||
|
||||
const mockResponse: User = {
|
||||
id: 1,
|
||||
username: 'test',
|
||||
name: 'Test',
|
||||
email: 'test@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and',
|
||||
filterSortingMode: 'alphabetical',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||
|
||||
service.getMyself().subscribe(user => {
|
||||
requiredSettings.forEach(setting => {
|
||||
expect(user.userSettings).toHaveProperty(setting);
|
||||
expect(user.userSettings[setting as keyof typeof user.userSettings]).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns User without required id field', () => {
|
||||
const invalidResponse = {
|
||||
username: 'test',
|
||||
name: 'Test',
|
||||
email: 'test@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {},
|
||||
userSettings: {}
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
|
||||
service.getMyself().subscribe(user => {
|
||||
expect(user).not.toHaveProperty('id');
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns User without permissions', () => {
|
||||
const invalidResponse = {
|
||||
id: 1,
|
||||
username: 'test',
|
||||
name: 'Test',
|
||||
email: 'test@test.com',
|
||||
assignedLibraries: [],
|
||||
userSettings: {}
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
|
||||
service.getMyself().subscribe(user => {
|
||||
expect(user).not.toHaveProperty('permissions');
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns User without userSettings', () => {
|
||||
const invalidResponse = {
|
||||
id: 1,
|
||||
username: 'test',
|
||||
name: 'Test',
|
||||
email: 'test@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {}
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
|
||||
service.getMyself().subscribe(user => {
|
||||
expect(user).not.toHaveProperty('userSettings');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Enum value contract', () => {
|
||||
it('should validate CbxPageSpread enum values from API', () => {
|
||||
const validValues = [CbxPageSpread.EVEN, CbxPageSpread.ODD];
|
||||
expect(validValues).toContain(CbxPageSpread.EVEN);
|
||||
expect(validValues).toContain(CbxPageSpread.ODD);
|
||||
expect(Object.keys(CbxPageSpread)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should validate CbxPageViewMode enum values from API', () => {
|
||||
const validValues = [CbxPageViewMode.SINGLE_PAGE, CbxPageViewMode.TWO_PAGE];
|
||||
expect(validValues).toContain(CbxPageViewMode.SINGLE_PAGE);
|
||||
expect(validValues).toContain(CbxPageViewMode.TWO_PAGE);
|
||||
expect(Object.keys(CbxPageViewMode)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should validate CbxFitMode enum values from API', () => {
|
||||
const validValues = [
|
||||
CbxFitMode.ACTUAL_SIZE,
|
||||
CbxFitMode.FIT_PAGE,
|
||||
CbxFitMode.FIT_WIDTH,
|
||||
CbxFitMode.FIT_HEIGHT,
|
||||
CbxFitMode.AUTO
|
||||
];
|
||||
validValues.forEach(value => {
|
||||
expect(Object.values(CbxFitMode)).toContain(value);
|
||||
});
|
||||
expect(Object.keys(CbxFitMode)).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('should validate PdfPageSpread enum values from API', () => {
|
||||
const validValues = [PdfPageSpread.EVEN, PdfPageSpread.ODD];
|
||||
expect(validValues).toContain(PdfPageSpread.EVEN);
|
||||
expect(validValues).toContain(PdfPageSpread.ODD);
|
||||
expect(Object.keys(PdfPageSpread)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should validate PdfPageViewMode enum values from API', () => {
|
||||
const validValues = [PdfPageViewMode.SINGLE_PAGE, PdfPageViewMode.TWO_PAGE];
|
||||
expect(validValues).toContain(PdfPageViewMode.SINGLE_PAGE);
|
||||
expect(validValues).toContain(PdfPageViewMode.TWO_PAGE);
|
||||
expect(Object.keys(PdfPageViewMode)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HTTP endpoint contract', () => {
|
||||
it('should call correct endpoint for getMyself', () => {
|
||||
httpClientMock.get.mockReturnValue(of({}));
|
||||
service.getMyself().subscribe();
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/me$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for getUsers', () => {
|
||||
httpClientMock.get.mockReturnValue(of([]));
|
||||
service.getUsers().subscribe();
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for createUser', () => {
|
||||
httpClientMock.post.mockReturnValue(of(void 0));
|
||||
const userData = {
|
||||
username: 'new',
|
||||
name: 'New User',
|
||||
email: 'new@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and' as const,
|
||||
filterSortingMode: 'alphabetical' as const,
|
||||
metadataCenterViewMode: 'route' as const,
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
};
|
||||
service.createUser(userData).subscribe();
|
||||
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/auth\/register$/),
|
||||
userData
|
||||
);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for updateUser', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
service.updateUser(123, {name: 'Updated'}).subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/users\/123$/),
|
||||
{name: 'Updated'}
|
||||
);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for deleteUser', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
service.deleteUser(123).subscribe();
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/123$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for changeUserPassword', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.changeUserPassword(123, 'newpass').subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/users\/change-user-password$/),
|
||||
{userId: 123, newPassword: 'newpass'}
|
||||
);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for changePassword', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.changePassword('oldpass', 'newpass').subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/users\/change-password$/),
|
||||
{currentPassword: 'oldpass', newPassword: 'newpass'}
|
||||
);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for updateUserSetting', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.updateUserSetting(123, 'koReaderEnabled', true);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/users\/123\/settings$/),
|
||||
{key: 'koReaderEnabled', value: true},
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Request payload contract', () => {
|
||||
it('should send UserUpdateRequest with correct structure', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
const updateRequest: UserUpdateRequest = {
|
||||
name: 'New Name',
|
||||
email: 'newemail@test.com',
|
||||
permissions: {
|
||||
admin: true,
|
||||
canUpload: true,
|
||||
canDownload: true,
|
||||
canEmailBook: true,
|
||||
canDeleteBook: true,
|
||||
canEditMetadata: true,
|
||||
canManageLibrary: true,
|
||||
canManageMetadataConfig: true,
|
||||
canSyncKoReader: true,
|
||||
canSyncKobo: true,
|
||||
canAccessOpds: true,
|
||||
canAccessBookdrop: true,
|
||||
canAccessLibraryStats: true,
|
||||
canAccessUserStats: true,
|
||||
canAccessTaskManager: true,
|
||||
canManageEmailConfig: true,
|
||||
canManageGlobalPreferences: true,
|
||||
canManageIcons: true,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: true,
|
||||
canBulkCustomFetchMetadata: true,
|
||||
canBulkEditMetadata: true,
|
||||
canBulkRegenerateCover: true,
|
||||
canMoveOrganizeFiles: true,
|
||||
canBulkLockUnlockMetadata: true
|
||||
},
|
||||
assignedLibraries: [1, 2, 3]
|
||||
};
|
||||
service.updateUser(1, updateRequest).subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
updateRequest
|
||||
);
|
||||
});
|
||||
|
||||
it('should send change password payload with correct structure', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.changePassword('current', 'new').subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
{currentPassword: 'current', newPassword: 'new'}
|
||||
);
|
||||
});
|
||||
|
||||
it('should send change user password payload with correct structure', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.changeUserPassword(456, 'newpassword').subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
{userId: 456, newPassword: 'newpassword'}
|
||||
);
|
||||
});
|
||||
|
||||
it('should send user setting payload with correct structure', () => {
|
||||
httpClientMock.put.mockReturnValue(of(void 0));
|
||||
service.updateUserSetting(789, 'enableSeriesView', false);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
{key: 'enableSeriesView', value: false},
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Response type contract', () => {
|
||||
it('should expect User array from getUsers', () => {
|
||||
const mockUsers: User[] = [{
|
||||
id: 1,
|
||||
username: 'user1',
|
||||
name: 'User One',
|
||||
email: 'user1@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and',
|
||||
filterSortingMode: 'alphabetical',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
}];
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(mockUsers));
|
||||
service.getUsers().subscribe(users => {
|
||||
expect(Array.isArray(users)).toBe(true);
|
||||
expect(users[0]).toHaveProperty('id');
|
||||
expect(users[0]).toHaveProperty('username');
|
||||
});
|
||||
});
|
||||
|
||||
it('should expect User from updateUser', () => {
|
||||
const mockUser: User = {
|
||||
id: 1,
|
||||
username: 'updated',
|
||||
name: 'Updated User',
|
||||
email: 'updated@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and',
|
||||
filterSortingMode: 'alphabetical',
|
||||
metadataCenterViewMode: 'route',
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
};
|
||||
|
||||
httpClientMock.put.mockReturnValue(of(mockUser));
|
||||
service.updateUser(1, {name: 'Updated User'}).subscribe(user => {
|
||||
expect(user).toHaveProperty('id');
|
||||
expect(user).toHaveProperty('username');
|
||||
expect(user).toHaveProperty('permissions');
|
||||
expect(user).toHaveProperty('userSettings');
|
||||
});
|
||||
});
|
||||
|
||||
it('should expect void from createUser', () => {
|
||||
httpClientMock.post.mockReturnValue(of(void 0));
|
||||
const userData = {
|
||||
username: 'new',
|
||||
name: 'New',
|
||||
email: 'new@test.com',
|
||||
assignedLibraries: [],
|
||||
permissions: {
|
||||
admin: false,
|
||||
canUpload: false,
|
||||
canDownload: false,
|
||||
canEmailBook: false,
|
||||
canDeleteBook: false,
|
||||
canEditMetadata: false,
|
||||
canManageLibrary: false,
|
||||
canManageMetadataConfig: false,
|
||||
canSyncKoReader: false,
|
||||
canSyncKobo: false,
|
||||
canAccessOpds: false,
|
||||
canAccessBookdrop: false,
|
||||
canAccessLibraryStats: false,
|
||||
canAccessUserStats: false,
|
||||
canAccessTaskManager: false,
|
||||
canManageEmailConfig: false,
|
||||
canManageGlobalPreferences: false,
|
||||
canManageIcons: false,
|
||||
canManageFonts: false,
|
||||
demoUser: false,
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canMoveOrganizeFiles: false,
|
||||
canBulkLockUnlockMetadata: false
|
||||
},
|
||||
userSettings: {
|
||||
perBookSetting: {pdf: '', epub: '', cbx: ''},
|
||||
pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false},
|
||||
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
|
||||
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
|
||||
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
|
||||
sidebarLibrarySorting: {field: '', order: ''},
|
||||
sidebarShelfSorting: {field: '', order: ''},
|
||||
sidebarMagicShelfSorting: {field: '', order: ''},
|
||||
filterMode: 'and' as const,
|
||||
filterSortingMode: 'alphabetical' as const,
|
||||
metadataCenterViewMode: 'route' as const,
|
||||
enableSeriesView: true,
|
||||
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
|
||||
koReaderEnabled: false,
|
||||
autoSaveMetadata: false
|
||||
}
|
||||
};
|
||||
service.createUser(userData).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,7 @@ export interface EntityViewPreference {
|
||||
view: 'GRID' | 'TABLE';
|
||||
coverSize: number;
|
||||
seriesCollapsed: boolean;
|
||||
overlayBookType: boolean;
|
||||
}
|
||||
|
||||
export interface EntityViewPreferenceOverride {
|
||||
@@ -96,6 +97,21 @@ export enum CbxScrollMode {
|
||||
INFINITE = 'INFINITE'
|
||||
}
|
||||
|
||||
export interface EbookReaderSetting {
|
||||
lineHeight: number;
|
||||
justify: boolean;
|
||||
hyphenate: boolean;
|
||||
maxColumnCount: number;
|
||||
gap: number;
|
||||
fontSize: number;
|
||||
theme: string
|
||||
maxInlineSize: number;
|
||||
maxBlockSize: number;
|
||||
fontFamily: string;
|
||||
isDark: boolean;
|
||||
flow: 'paginated' | 'scrolled';
|
||||
}
|
||||
|
||||
export interface EpubReaderSetting {
|
||||
theme: string;
|
||||
font: string;
|
||||
@@ -131,6 +147,7 @@ export interface UserSettings {
|
||||
perBookSetting: PerBookSetting;
|
||||
pdfReaderSetting: PdfReaderSetting;
|
||||
epubReaderSetting: EpubReaderSetting;
|
||||
ebookReaderSetting: EbookReaderSetting;
|
||||
cbxReaderSetting: CbxReaderSetting;
|
||||
newPdfReaderSetting: NewPdfReaderSetting;
|
||||
sidebarLibrarySorting: SidebarLibrarySorting;
|
||||
|
||||
+4
-3
@@ -170,8 +170,8 @@ export class ViewPreferencesComponent implements OnInit, OnDestroy {
|
||||
options.map(opt => ({...opt, entityType}));
|
||||
|
||||
return [...withEntityType(this.libraryOptions, 'LIBRARY'),
|
||||
...withEntityType(this.shelfOptions, 'SHELF'),
|
||||
...withEntityType(this.magicShelfOptions, 'MAGIC_SHELF')]
|
||||
...withEntityType(this.shelfOptions, 'SHELF'),
|
||||
...withEntityType(this.magicShelfOptions, 'MAGIC_SHELF')]
|
||||
.filter(opt => !used.has(`${opt.entityType}_${opt.value}`));
|
||||
}
|
||||
|
||||
@@ -217,7 +217,8 @@ export class ViewPreferencesComponent implements OnInit, OnDestroy {
|
||||
sortDir: o.sortDir,
|
||||
view: o.view,
|
||||
coverSize: existing?.coverSize ?? 1.0,
|
||||
seriesCollapsed: existing?.seriesCollapsed ?? false
|
||||
seriesCollapsed: existing?.seriesCollapsed ?? false,
|
||||
overlayBookType: existing?.overlayBookType ?? true
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
@@ -22,7 +22,10 @@ const BOOK_TYPE_COLORS = {
|
||||
'CBZ': '#27a153',
|
||||
'CBX': '#d4b50f',
|
||||
'CBR': '#e67e22',
|
||||
'CB7': '#9b59b6'
|
||||
'CB7': '#9b59b6',
|
||||
'FB2': '#1abc9c',
|
||||
'MOBI': '#f39c12',
|
||||
'AZW3': '#2ecc71'
|
||||
} as const;
|
||||
|
||||
const CHART_DEFAULTS = {
|
||||
|
||||
@@ -88,7 +88,7 @@
|
||||
name="file"
|
||||
[customUpload]="true"
|
||||
[multiple]="true"
|
||||
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2"
|
||||
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3"
|
||||
(onSelect)="onFilesSelect($event)"
|
||||
(uploadHandler)="uploadFiles($event)"
|
||||
[disabled]="value === 'library' ? (!selectedLibrary || !selectedPath) : false">
|
||||
|
||||
@@ -181,9 +181,9 @@ export class ReadingSessionService {
|
||||
endTime: endTime.toISOString(),
|
||||
durationSeconds,
|
||||
durationFormatted: this.formatDuration(durationSeconds),
|
||||
startProgress: session.startProgress,
|
||||
endProgress: session.endProgress,
|
||||
progressDelta: session.progressDelta,
|
||||
startProgress: session.startProgress != null ? Math.round(session.startProgress * 100) / 100 : undefined,
|
||||
endProgress: session.endProgress != null ? Math.round(session.endProgress * 100) / 100 : undefined,
|
||||
progressDelta: session.progressDelta != null ? Math.round(session.progressDelta * 100) / 100 : undefined,
|
||||
startLocation: session.startLocation,
|
||||
endLocation: session.endLocation
|
||||
};
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export const makeComicBook = ({ entries, loadBlob, getSize }, file) => {
|
||||
const cache = new Map()
|
||||
const urls = new Map()
|
||||
const load = async name => {
|
||||
if (cache.has(name)) return cache.get(name)
|
||||
const src = URL.createObjectURL(await loadBlob(name))
|
||||
const page = URL.createObjectURL(
|
||||
new Blob([`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="margin: 0"><img src="${src}"></body></html>`], { type: 'text/html' }))
|
||||
urls.set(name, [src, page])
|
||||
cache.set(name, page)
|
||||
return page
|
||||
}
|
||||
const unload = name => {
|
||||
urls.get(name)?.forEach?.(url => URL.revokeObjectURL(url))
|
||||
urls.delete(name)
|
||||
cache.delete(name)
|
||||
}
|
||||
|
||||
const exts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.jxl', '.avif']
|
||||
const files = entries
|
||||
.map(entry => entry.filename)
|
||||
.filter(name => exts.some(ext => name.endsWith(ext)))
|
||||
.sort()
|
||||
if (!files.length) throw new Error('No supported image files in archive')
|
||||
|
||||
const book = {}
|
||||
book.getCover = () => loadBlob(files[0])
|
||||
book.metadata = { title: file.name }
|
||||
book.sections = files.map(name => ({
|
||||
id: name,
|
||||
load: () => load(name),
|
||||
unload: () => unload(name),
|
||||
size: getSize(name),
|
||||
}))
|
||||
book.toc = files.map(name => ({ label: name, href: name }))
|
||||
book.rendition = { layout: 'pre-paginated' }
|
||||
book.resolveHref = href => ({ index: book.sections.findIndex(s => s.id === href) })
|
||||
book.splitTOCHref = href => [href, null]
|
||||
book.getTOCFragment = doc => doc.documentElement
|
||||
book.destroy = () => {
|
||||
for (const arr of urls.values())
|
||||
for (const url of arr) URL.revokeObjectURL(url)
|
||||
}
|
||||
return book
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
const decoder = new TextDecoder()
|
||||
const decode = decoder.decode.bind(decoder)
|
||||
|
||||
const concatTypedArray = (a, b) => {
|
||||
const result = new a.constructor(a.length + b.length)
|
||||
result.set(a)
|
||||
result.set(b, a.length)
|
||||
return result
|
||||
}
|
||||
|
||||
const strcmp = (a, b) => {
|
||||
a = a.toLowerCase(), b = b.toLowerCase()
|
||||
return a < b ? -1 : a > b ? 1 : 0
|
||||
}
|
||||
|
||||
class DictZip {
|
||||
#chlen
|
||||
#chunks
|
||||
#compressed
|
||||
inflate
|
||||
async load(file) {
|
||||
const header = new DataView(await file.slice(0, 12).arrayBuffer())
|
||||
if (header.getUint8(0) !== 31 || header.getUint8(1) !== 139
|
||||
|| header.getUint8(2) !== 8) throw new Error('Not a DictZip file')
|
||||
const flg = header.getUint8(3)
|
||||
if (!flg & 0b100) throw new Error('Missing FEXTRA flag')
|
||||
|
||||
const xlen = header.getUint16(10, true)
|
||||
const extra = new DataView(await file.slice(12, 12 + xlen).arrayBuffer())
|
||||
if (extra.getUint8(0) !== 82 || extra.getUint8(1) !== 65)
|
||||
throw new Error('Subfield ID should be RA')
|
||||
if (extra.getUint16(4, true) !== 1) throw new Error('Unsupported version')
|
||||
|
||||
this.#chlen = extra.getUint16(6, true)
|
||||
const chcnt = extra.getUint16(8, true)
|
||||
this.#chunks = []
|
||||
for (let i = 0, chunkOffset = 0; i < chcnt; i++) {
|
||||
const chunkSize = extra.getUint16(10 + 2 * i, true)
|
||||
this.#chunks.push([chunkOffset, chunkSize])
|
||||
chunkOffset = chunkOffset + chunkSize
|
||||
}
|
||||
|
||||
// skip to compressed data
|
||||
let offset = 12 + xlen
|
||||
const max = Math.min(offset + 512, file.size)
|
||||
const strArr = new Uint8Array(await file.slice(0, max).arrayBuffer())
|
||||
if (flg & 0b1000) { // fname
|
||||
const i = strArr.indexOf(0, offset)
|
||||
if (i < 0) throw new Error('Header too long')
|
||||
offset = i + 1
|
||||
}
|
||||
if (flg & 0b10000) { // fcomment
|
||||
const i = strArr.indexOf(0, offset)
|
||||
if (i < 0) throw new Error('Header too long')
|
||||
offset = i + 1
|
||||
}
|
||||
if (flg & 0b10) offset += 2 // fhcrc
|
||||
this.#compressed = file.slice(offset)
|
||||
}
|
||||
async read(offset, size) {
|
||||
const chunks = this.#chunks
|
||||
const startIndex = Math.trunc(offset / this.#chlen)
|
||||
const endIndex = Math.trunc((offset + size) / this.#chlen)
|
||||
const buf = await this.#compressed.slice(chunks[startIndex][0],
|
||||
chunks[endIndex][0] + chunks[endIndex][1]).arrayBuffer()
|
||||
let arr = new Uint8Array()
|
||||
for (let pos = 0, i = startIndex; i <= endIndex; i++) {
|
||||
const data = new Uint8Array(buf, pos, chunks[i][1])
|
||||
arr = concatTypedArray(arr, await this.inflate(data))
|
||||
pos += chunks[i][1]
|
||||
}
|
||||
const startOffset = offset - startIndex * this.#chlen
|
||||
return arr.subarray(startOffset, startOffset + size)
|
||||
}
|
||||
}
|
||||
|
||||
class Index {
|
||||
strcmp = strcmp
|
||||
// binary search
|
||||
bisect(query, start = 0, end = this.words.length - 1) {
|
||||
if (end - start === 1) {
|
||||
if (!this.strcmp(query, this.getWord(start))) return start
|
||||
if (!this.strcmp(query, this.getWord(end))) return end
|
||||
return null
|
||||
}
|
||||
const mid = Math.floor(start + (end - start) / 2)
|
||||
const cmp = this.strcmp(query, this.getWord(mid))
|
||||
if (cmp < 0) return this.bisect(query, start, mid)
|
||||
if (cmp > 0) return this.bisect(query, mid, end)
|
||||
return mid
|
||||
}
|
||||
// check for multiple definitions
|
||||
checkAdjacent(query, i) {
|
||||
if (i == null) return []
|
||||
let j = i
|
||||
const equals = i => {
|
||||
const word = this.getWord(i)
|
||||
return word ? this.strcmp(query, word) === 0 : false
|
||||
}
|
||||
while (equals(j - 1)) j--
|
||||
let k = i
|
||||
while (equals(k + 1)) k++
|
||||
return j === k ? [i] : Array.from({ length: k + 1 - j }, (_, i) => j + i)
|
||||
}
|
||||
lookup(query) {
|
||||
return this.checkAdjacent(query, this.bisect(query))
|
||||
}
|
||||
}
|
||||
|
||||
const decodeBase64Number = str => {
|
||||
const { length } = str
|
||||
let n = 0
|
||||
for (let i = 0; i < length; i++) {
|
||||
const c = str.charCodeAt(i)
|
||||
n += (c === 43 ? 62 // "+"
|
||||
: c === 47 ? 63 // "/"
|
||||
: c < 58 ? c + 4 // 0-9 -> 52-61
|
||||
: c < 91 ? c - 65 // A-Z -> 0-25
|
||||
: c - 71 // a-z -> 26-51
|
||||
) * 64 ** (length - 1 - i)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
class DictdIndex extends Index {
|
||||
getWord(i) {
|
||||
return this.words[i]
|
||||
}
|
||||
async load(file) {
|
||||
const words = []
|
||||
const offsets = []
|
||||
const sizes = []
|
||||
for (const line of decode(await file.arrayBuffer()).split('\n')) {
|
||||
const a = line.split('\t')
|
||||
words.push(a[0])
|
||||
offsets.push(decodeBase64Number(a[1]))
|
||||
sizes.push(decodeBase64Number(a[2]))
|
||||
}
|
||||
this.words = words
|
||||
this.offsets = offsets
|
||||
this.sizes = sizes
|
||||
}
|
||||
}
|
||||
|
||||
export class DictdDict {
|
||||
#dict = new DictZip()
|
||||
#idx = new DictdIndex()
|
||||
loadDict(file, inflate) {
|
||||
this.#dict.inflate = inflate
|
||||
return this.#dict.load(file)
|
||||
}
|
||||
async #readWord(i) {
|
||||
const word = this.#idx.getWord(i)
|
||||
const offset = this.#idx.offsets[i]
|
||||
const size = this.#idx.sizes[i]
|
||||
return { word, data: ['m', this.#dict.read(offset, size)] }
|
||||
}
|
||||
#readWords(arr) {
|
||||
return Promise.all(arr.map(this.#readWord.bind(this)))
|
||||
}
|
||||
lookup(query) {
|
||||
return this.#readWords(this.#idx.lookup(query))
|
||||
}
|
||||
}
|
||||
|
||||
class StarDictIndex extends Index {
|
||||
isSyn
|
||||
#arr
|
||||
getWord(i) {
|
||||
const word = this.words[i]
|
||||
if (!word) return
|
||||
return decode(this.#arr.subarray(word[0], word[1]))
|
||||
}
|
||||
async load(file) {
|
||||
const { isSyn } = this
|
||||
const buf = await file.arrayBuffer()
|
||||
const arr = new Uint8Array(buf)
|
||||
this.#arr = arr
|
||||
const view = new DataView(buf)
|
||||
const words = []
|
||||
const offsets = []
|
||||
const sizes = []
|
||||
for (let i = 0; i < arr.length;) {
|
||||
const newI = arr.subarray(0, i + 256).indexOf(0, i)
|
||||
if (newI < 0) throw new Error('Word too big')
|
||||
words.push([i, newI])
|
||||
offsets.push(view.getUint32(newI + 1))
|
||||
if (isSyn) i = newI + 5
|
||||
else {
|
||||
sizes.push(view.getUint32(newI + 5))
|
||||
i = newI + 9
|
||||
}
|
||||
}
|
||||
this.words = words
|
||||
this.offsets = offsets
|
||||
this.sizes = sizes
|
||||
}
|
||||
}
|
||||
|
||||
export class StarDict {
|
||||
#dict = new DictZip()
|
||||
#idx = new StarDictIndex()
|
||||
#syn = Object.assign(new StarDictIndex(), { isSyn: true })
|
||||
async loadIfo(file) {
|
||||
const str = decode(await file.arrayBuffer())
|
||||
this.ifo = Object.fromEntries(str.split('\n').map(line => {
|
||||
const sep = line.indexOf('=')
|
||||
if (sep < 0) return
|
||||
return [line.slice(0, sep), line.slice(sep + 1)]
|
||||
}).filter(x => x))
|
||||
}
|
||||
loadDict(file, inflate) {
|
||||
this.#dict.inflate = inflate
|
||||
return this.#dict.load(file)
|
||||
}
|
||||
loadIdx(file) {
|
||||
return this.#idx.load(file)
|
||||
}
|
||||
loadSyn(file) {
|
||||
if (file) return this.#syn.load(file)
|
||||
}
|
||||
async #readWord(i) {
|
||||
const word = this.#idx.getWord(i)
|
||||
const offset = this.#idx.offsets[i]
|
||||
const size = this.#idx.sizes[i]
|
||||
const data = await this.#dict.read(offset, size)
|
||||
const seq = this.ifo.sametypesequence
|
||||
if (!seq) throw new Error('TODO')
|
||||
if (seq.length === 1) return { word, data: [[seq[0], data]] }
|
||||
throw new Error('TODO')
|
||||
}
|
||||
#readWords(arr) {
|
||||
return Promise.all(arr.map(this.#readWord.bind(this)))
|
||||
}
|
||||
lookup(query) {
|
||||
return this.#readWords(this.#idx.lookup(query))
|
||||
}
|
||||
synonyms(query) {
|
||||
return this.#readWords(this.#syn.lookup(query).map(i => this.#syn.offsets[i]))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,345 @@
|
||||
const findIndices = (arr, f) => arr
|
||||
.map((x, i, a) => f(x, i, a) ? i : null).filter(x => x != null)
|
||||
const splitAt = (arr, is) => [-1, ...is, arr.length].reduce(({ xs, a }, b) =>
|
||||
({ xs: xs?.concat([arr.slice(a + 1, b)]) ?? [], a: b }), {}).xs
|
||||
const concatArrays = (a, b) =>
|
||||
a.slice(0, -1).concat([a[a.length - 1].concat(b[0])]).concat(b.slice(1))
|
||||
|
||||
const isNumber = /\d/
|
||||
export const isCFI = /^epubcfi\((.*)\)$/
|
||||
const escapeCFI = str => str.replace(/[\^[\](),;=]/g, '^$&')
|
||||
|
||||
const wrap = x => isCFI.test(x) ? x : `epubcfi(${x})`
|
||||
const unwrap = x => x.match(isCFI)?.[1] ?? x
|
||||
const lift = f => (...xs) =>
|
||||
`epubcfi(${f(...xs.map(x => x.match(isCFI)?.[1] ?? x))})`
|
||||
export const joinIndir = lift((...xs) => xs.join('!'))
|
||||
|
||||
const tokenizer = str => {
|
||||
const tokens = []
|
||||
let state, escape, value = ''
|
||||
const push = x => (tokens.push(x), state = null, value = '')
|
||||
const cat = x => (value += x, escape = false)
|
||||
for (const char of Array.from(str.trim()).concat('')) {
|
||||
if (char === '^' && !escape) {
|
||||
escape = true
|
||||
continue
|
||||
}
|
||||
if (state === '!') push(['!'])
|
||||
else if (state === ',') push([','])
|
||||
else if (state === '/' || state === ':') {
|
||||
if (isNumber.test(char)) {
|
||||
cat(char)
|
||||
continue
|
||||
} else push([state, parseInt(value)])
|
||||
} else if (state === '~') {
|
||||
if (isNumber.test(char) || char === '.') {
|
||||
cat(char)
|
||||
continue
|
||||
} else push(['~', parseFloat(value)])
|
||||
} else if (state === '@') {
|
||||
if (char === ':') {
|
||||
push(['@', parseFloat(value)])
|
||||
state = '@'
|
||||
continue
|
||||
}
|
||||
if (isNumber.test(char) || char === '.') {
|
||||
cat(char)
|
||||
continue
|
||||
} else push(['@', parseFloat(value)])
|
||||
} else if (state === '[') {
|
||||
if (char === ';' && !escape) {
|
||||
push(['[', value])
|
||||
state = ';'
|
||||
} else if (char === ',' && !escape) {
|
||||
push(['[', value])
|
||||
state = '['
|
||||
} else if (char === ']' && !escape) push(['[', value])
|
||||
else cat(char)
|
||||
continue
|
||||
} else if (state?.startsWith(';')) {
|
||||
if (char === '=' && !escape) {
|
||||
state = `;${value}`
|
||||
value = ''
|
||||
} else if (char === ';' && !escape) {
|
||||
push([state, value])
|
||||
state = ';'
|
||||
} else if (char === ']' && !escape) push([state, value])
|
||||
else cat(char)
|
||||
continue
|
||||
}
|
||||
if (char === '/' || char === ':' || char === '~' || char === '@'
|
||||
|| char === '[' || char === '!' || char === ',') state = char
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
|
||||
const findTokens = (tokens, x) => findIndices(tokens, ([t]) => t === x)
|
||||
|
||||
const parser = tokens => {
|
||||
const parts = []
|
||||
let state
|
||||
for (const [type, val] of tokens) {
|
||||
if (type === '/') parts.push({ index: val })
|
||||
else {
|
||||
const last = parts[parts.length - 1]
|
||||
if (type === ':') last.offset = val
|
||||
else if (type === '~') last.temporal = val
|
||||
else if (type === '@') last.spatial = (last.spatial ?? []).concat(val)
|
||||
else if (type === ';s') last.side = val
|
||||
else if (type === '[') {
|
||||
if (state === '/' && val) last.id = val
|
||||
else {
|
||||
last.text = (last.text ?? []).concat(val)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
state = type
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
// split at step indirections, then parse each part
|
||||
const parserIndir = tokens =>
|
||||
splitAt(tokens, findTokens(tokens, '!')).map(parser)
|
||||
|
||||
export const parse = cfi => {
|
||||
const tokens = tokenizer(unwrap(cfi))
|
||||
const commas = findTokens(tokens, ',')
|
||||
if (!commas.length) return parserIndir(tokens)
|
||||
const [parent, start, end] = splitAt(tokens, commas).map(parserIndir)
|
||||
return { parent, start, end }
|
||||
}
|
||||
|
||||
const partToString = ({ index, id, offset, temporal, spatial, text, side }) => {
|
||||
const param = side ? `;s=${side}` : ''
|
||||
return `/${index}`
|
||||
+ (id ? `[${escapeCFI(id)}${param}]` : '')
|
||||
// "CFI expressions [..] SHOULD include an explicit character offset"
|
||||
+ (offset != null && index % 2 ? `:${offset}` : '')
|
||||
+ (temporal ? `~${temporal}` : '')
|
||||
+ (spatial ? `@${spatial.join(':')}` : '')
|
||||
+ (text || (!id && side) ? '['
|
||||
+ (text?.map(escapeCFI)?.join(',') ?? '')
|
||||
+ param + ']' : '')
|
||||
}
|
||||
|
||||
const toInnerString = parsed => parsed.parent
|
||||
? [parsed.parent, parsed.start, parsed.end].map(toInnerString).join(',')
|
||||
: parsed.map(parts => parts.map(partToString).join('')).join('!')
|
||||
|
||||
const toString = parsed => wrap(toInnerString(parsed))
|
||||
|
||||
export const collapse = (x, toEnd) => typeof x === 'string'
|
||||
? toString(collapse(parse(x), toEnd))
|
||||
: x.parent ? concatArrays(x.parent, x[toEnd ? 'end' : 'start']) : x
|
||||
|
||||
// create range CFI from two CFIs
|
||||
const buildRange = (from, to) => {
|
||||
if (typeof from === 'string') from = parse(from)
|
||||
if (typeof to === 'string') to = parse(to)
|
||||
from = collapse(from)
|
||||
to = collapse(to, true)
|
||||
// ranges across multiple documents are not allowed; handle local paths only
|
||||
const localFrom = from[from.length - 1], localTo = to[to.length - 1]
|
||||
const localParent = [], localStart = [], localEnd = []
|
||||
let pushToParent = true
|
||||
const len = Math.max(localFrom.length, localTo.length)
|
||||
for (let i = 0; i < len; i++) {
|
||||
const a = localFrom[i], b = localTo[i]
|
||||
pushToParent &&= a?.index === b?.index && !a?.offset && !b?.offset
|
||||
if (pushToParent) localParent.push(a)
|
||||
else {
|
||||
if (a) localStart.push(a)
|
||||
if (b) localEnd.push(b)
|
||||
}
|
||||
}
|
||||
// copy non-local paths from `from`
|
||||
const parent = from.slice(0, -1).concat([localParent])
|
||||
return toString({ parent, start: [localStart], end: [localEnd] })
|
||||
}
|
||||
|
||||
export const compare = (a, b) => {
|
||||
if (typeof a === 'string') a = parse(a)
|
||||
if (typeof b === 'string') b = parse(b)
|
||||
if (a.start || b.start) return compare(collapse(a), collapse(b))
|
||||
|| compare(collapse(a, true), collapse(b, true))
|
||||
|
||||
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
||||
const p = a[i] ?? [], q = b[i] ?? []
|
||||
const maxIndex = Math.max(p.length, q.length) - 1
|
||||
for (let i = 0; i <= maxIndex; i++) {
|
||||
const x = p[i], y = q[i]
|
||||
if (!x) return -1
|
||||
if (!y) return 1
|
||||
if (x.index > y.index) return 1
|
||||
if (x.index < y.index) return -1
|
||||
if (i === maxIndex) {
|
||||
// TODO: compare temporal & spatial offsets
|
||||
if (x.offset > y.offset) return 1
|
||||
if (x.offset < y.offset) return -1
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
const isTextNode = ({ nodeType }) => nodeType === 3 || nodeType === 4
|
||||
const isElementNode = ({ nodeType }) => nodeType === 1
|
||||
|
||||
const getChildNodes = (node, filter) => {
|
||||
const nodes = Array.from(node.childNodes)
|
||||
// "content other than element and character data is ignored"
|
||||
.filter(node => isTextNode(node) || isElementNode(node))
|
||||
return filter ? nodes.map(node => {
|
||||
const accept = filter(node)
|
||||
if (accept === NodeFilter.FILTER_REJECT) return null
|
||||
else if (accept === NodeFilter.FILTER_SKIP) return getChildNodes(node, filter)
|
||||
else return node
|
||||
}).flat().filter(x => x) : nodes
|
||||
}
|
||||
|
||||
// child nodes are organized such that the result is always
|
||||
// [element, text, element, text, ..., element],
|
||||
// regardless of the actual structure in the document;
|
||||
// so multiple text nodes need to be combined, and nonexistent ones counted;
|
||||
// see "Step Reference to Child Element or Character Data (/)" in EPUB CFI spec
|
||||
const indexChildNodes = (node, filter) => {
|
||||
const nodes = getChildNodes(node, filter)
|
||||
.reduce((arr, node) => {
|
||||
let last = arr[arr.length - 1]
|
||||
if (!last) arr.push(node)
|
||||
// "there is one chunk between each pair of child elements"
|
||||
else if (isTextNode(node)) {
|
||||
if (Array.isArray(last)) last.push(node)
|
||||
else if (isTextNode(last)) arr[arr.length - 1] = [last, node]
|
||||
else arr.push(node)
|
||||
} else {
|
||||
if (isElementNode(last)) arr.push(null, node)
|
||||
else arr.push(node)
|
||||
}
|
||||
return arr
|
||||
}, [])
|
||||
// "the first chunk is located before the first child element"
|
||||
if (isElementNode(nodes[0])) nodes.unshift('first')
|
||||
// "the last chunk is located after the last child element"
|
||||
if (isElementNode(nodes[nodes.length - 1])) nodes.push('last')
|
||||
// "'virtual' elements"
|
||||
nodes.unshift('before') // "0 is a valid index"
|
||||
nodes.push('after') // "n+2 is a valid index"
|
||||
return nodes
|
||||
}
|
||||
|
||||
const partsToNode = (node, parts, filter) => {
|
||||
const { id } = parts[parts.length - 1]
|
||||
if (id) {
|
||||
const el = node.ownerDocument.getElementById(id)
|
||||
if (el) return { node: el, offset: 0 }
|
||||
}
|
||||
for (const { index } of parts) {
|
||||
const newNode = node ? indexChildNodes(node, filter)[index] : null
|
||||
// handle non-existent nodes
|
||||
if (newNode === 'first') return { node: node.firstChild ?? node }
|
||||
if (newNode === 'last') return { node: node.lastChild ?? node }
|
||||
if (newNode === 'before') return { node, before: true }
|
||||
if (newNode === 'after') return { node, after: true }
|
||||
node = newNode
|
||||
}
|
||||
const { offset } = parts[parts.length - 1]
|
||||
if (!Array.isArray(node)) return { node, offset }
|
||||
// get underlying text node and offset from the chunk
|
||||
let sum = 0
|
||||
for (const n of node) {
|
||||
const { length } = n.nodeValue
|
||||
if (sum + length >= offset) return { node: n, offset: offset - sum }
|
||||
sum += length
|
||||
}
|
||||
}
|
||||
|
||||
const nodeToParts = (node, offset, filter) => {
|
||||
const { parentNode, id } = node
|
||||
const indexed = indexChildNodes(parentNode, filter)
|
||||
const index = indexed.findIndex(x =>
|
||||
Array.isArray(x) ? x.some(x => x === node) : x === node)
|
||||
// adjust offset as if merging the text nodes in the chunk
|
||||
const chunk = indexed[index]
|
||||
if (Array.isArray(chunk)) {
|
||||
let sum = 0
|
||||
for (const x of chunk) {
|
||||
if (x === node) {
|
||||
sum += offset
|
||||
break
|
||||
} else sum += x.nodeValue.length
|
||||
}
|
||||
offset = sum
|
||||
}
|
||||
const part = { id, index, offset }
|
||||
return (parentNode !== node.ownerDocument.documentElement
|
||||
? nodeToParts(parentNode, null, filter).concat(part) : [part])
|
||||
// remove ignored nodes
|
||||
.filter(x => x.index !== -1)
|
||||
}
|
||||
|
||||
export const fromRange = (range, filter) => {
|
||||
const { startContainer, startOffset, endContainer, endOffset } = range
|
||||
const start = nodeToParts(startContainer, startOffset, filter)
|
||||
if (range.collapsed) return toString([start])
|
||||
const end = nodeToParts(endContainer, endOffset, filter)
|
||||
return buildRange([start], [end])
|
||||
}
|
||||
|
||||
export const toRange = (doc, parts, filter) => {
|
||||
const startParts = collapse(parts)
|
||||
const endParts = collapse(parts, true)
|
||||
|
||||
const root = doc.documentElement
|
||||
const start = partsToNode(root, startParts[0], filter)
|
||||
const end = partsToNode(root, endParts[0], filter)
|
||||
|
||||
const range = doc.createRange()
|
||||
|
||||
if (start.before) range.setStartBefore(start.node)
|
||||
else if (start.after) range.setStartAfter(start.node)
|
||||
else range.setStart(start.node, start.offset)
|
||||
|
||||
if (end.before) range.setEndBefore(end.node)
|
||||
else if (end.after) range.setEndAfter(end.node)
|
||||
else range.setEnd(end.node, end.offset)
|
||||
return range
|
||||
}
|
||||
|
||||
// faster way of getting CFIs for sorted elements in a single parent
|
||||
export const fromElements = elements => {
|
||||
const results = []
|
||||
const { parentNode } = elements[0]
|
||||
const parts = nodeToParts(parentNode)
|
||||
for (const [index, node] of indexChildNodes(parentNode).entries()) {
|
||||
const el = elements[results.length]
|
||||
if (node === el)
|
||||
results.push(toString([parts.concat({ id: el.id, index })]))
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
export const toElement = (doc, parts) =>
|
||||
partsToNode(doc.documentElement, collapse(parts)).node
|
||||
|
||||
// turn indices into standard CFIs when you don't have an actual package document
|
||||
export const fake = {
|
||||
fromIndex: index => wrap(`/6/${(index + 1) * 2}`),
|
||||
toIndex: parts => parts?.at(-1).index / 2 - 1,
|
||||
}
|
||||
|
||||
// get CFI from Calibre bookmarks
|
||||
// see https://github.com/johnfactotum/foliate/issues/849
|
||||
export const fromCalibrePos = pos => {
|
||||
const [parts] = parse(pos)
|
||||
const item = parts.shift()
|
||||
parts.shift()
|
||||
return toString([[{ index: 6 }, item], parts])
|
||||
}
|
||||
export const fromCalibreHighlight = ({ spine_index, start_cfi, end_cfi }) => {
|
||||
const pre = fake.fromIndex(spine_index) + '!'
|
||||
return buildRange(pre + start_cfi.slice(2), pre + end_cfi.slice(2))
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
const normalizeWhitespace = str => str ? str
|
||||
.replace(/[\t\n\f\r ]+/g, ' ')
|
||||
.replace(/^[\t\n\f\r ]+/, '')
|
||||
.replace(/[\t\n\f\r ]+$/, '') : ''
|
||||
const getElementText = el => normalizeWhitespace(el?.textContent)
|
||||
|
||||
const NS = {
|
||||
XLINK: 'http://www.w3.org/1999/xlink',
|
||||
EPUB: 'http://www.idpf.org/2007/ops',
|
||||
}
|
||||
|
||||
const MIME = {
|
||||
XML: 'application/xml',
|
||||
XHTML: 'application/xhtml+xml',
|
||||
}
|
||||
|
||||
const STYLE = {
|
||||
'strong': ['strong', 'self'],
|
||||
'emphasis': ['em', 'self'],
|
||||
'style': ['span', 'self'],
|
||||
'a': 'anchor',
|
||||
'strikethrough': ['s', 'self'],
|
||||
'sub': ['sub', 'self'],
|
||||
'sup': ['sup', 'self'],
|
||||
'code': ['code', 'self'],
|
||||
'image': 'image',
|
||||
}
|
||||
|
||||
const TABLE = {
|
||||
'tr': ['tr', {
|
||||
'th': ['th', STYLE, ['colspan', 'rowspan', 'align', 'valign']],
|
||||
'td': ['td', STYLE, ['colspan', 'rowspan', 'align', 'valign']],
|
||||
}, ['align']],
|
||||
}
|
||||
|
||||
const POEM = {
|
||||
'epigraph': ['blockquote'],
|
||||
'subtitle': ['h2', STYLE],
|
||||
'text-author': ['p', STYLE],
|
||||
'date': ['p', STYLE],
|
||||
'stanza': 'stanza',
|
||||
}
|
||||
|
||||
const SECTION = {
|
||||
'title': ['header', {
|
||||
'p': ['h1', STYLE],
|
||||
'empty-line': ['br'],
|
||||
}],
|
||||
'epigraph': ['blockquote', 'self'],
|
||||
'image': 'image',
|
||||
'annotation': ['aside'],
|
||||
'section': ['section', 'self'],
|
||||
'p': ['p', STYLE],
|
||||
'poem': ['blockquote', POEM],
|
||||
'subtitle': ['h2', STYLE],
|
||||
'cite': ['blockquote', 'self'],
|
||||
'empty-line': ['br'],
|
||||
'table': ['table', TABLE],
|
||||
'text-author': ['p', STYLE],
|
||||
}
|
||||
POEM['epigraph'].push(SECTION)
|
||||
|
||||
const BODY = {
|
||||
'image': 'image',
|
||||
'title': ['section', {
|
||||
'p': ['h1', STYLE],
|
||||
'empty-line': ['br'],
|
||||
}],
|
||||
'epigraph': ['section', SECTION],
|
||||
'section': ['section', SECTION],
|
||||
}
|
||||
|
||||
class FB2Converter {
|
||||
constructor(fb2) {
|
||||
this.fb2 = fb2
|
||||
this.doc = document.implementation.createDocument(NS.XHTML, 'html')
|
||||
// use this instead of `getElementById` to allow images like
|
||||
// `<image l:href="#img1.jpg" id="img1.jpg" />`
|
||||
this.bins = new Map(Array.from(this.fb2.getElementsByTagName('binary'),
|
||||
el => [el.id, el]))
|
||||
}
|
||||
getImageSrc(el) {
|
||||
const href = el.getAttributeNS(NS.XLINK, 'href')
|
||||
if (!href) return 'data:,'
|
||||
const [, id] = href.split('#')
|
||||
if (!id) return href
|
||||
const bin = this.bins.get(id)
|
||||
return bin
|
||||
? `data:${bin.getAttribute('content-type')};base64,${bin.textContent}`
|
||||
: href
|
||||
}
|
||||
image(node) {
|
||||
const el = this.doc.createElement('img')
|
||||
el.alt = node.getAttribute('alt')
|
||||
el.title = node.getAttribute('title')
|
||||
el.setAttribute('src', this.getImageSrc(node))
|
||||
return el
|
||||
}
|
||||
anchor(node) {
|
||||
const el = this.convert(node, { 'a': ['a', STYLE] })
|
||||
el.setAttribute('href', node.getAttributeNS(NS.XLINK, 'href'))
|
||||
if (node.getAttribute('type') === 'note')
|
||||
el.setAttributeNS(NS.EPUB, 'epub:type', 'noteref')
|
||||
return el
|
||||
}
|
||||
stanza(node) {
|
||||
const el = this.convert(node, {
|
||||
'stanza': ['p', {
|
||||
'title': ['header', {
|
||||
'p': ['strong', STYLE],
|
||||
'empty-line': ['br'],
|
||||
}],
|
||||
'subtitle': ['p', STYLE],
|
||||
}],
|
||||
})
|
||||
for (const child of node.children) if (child.nodeName === 'v') {
|
||||
el.append(this.doc.createTextNode(child.textContent))
|
||||
el.append(this.doc.createElement('br'))
|
||||
}
|
||||
return el
|
||||
}
|
||||
convert(node, def) {
|
||||
// not an element; return text content
|
||||
if (node.nodeType === 3) return this.doc.createTextNode(node.textContent)
|
||||
if (node.nodeType === 4) return this.doc.createCDATASection(node.textContent)
|
||||
if (node.nodeType === 8) return this.doc.createComment(node.textContent)
|
||||
|
||||
const d = def?.[node.nodeName]
|
||||
if (!d) return null
|
||||
if (typeof d === 'string') return this[d](node)
|
||||
|
||||
const [name, opts, attrs] = d
|
||||
const el = this.doc.createElement(name)
|
||||
|
||||
// copy the ID, and set class name from original element name
|
||||
if (node.id) el.id = node.id
|
||||
el.classList.add(node.nodeName)
|
||||
|
||||
// copy attributes
|
||||
if (Array.isArray(attrs)) for (const attr of attrs) {
|
||||
const value = node.getAttribute(attr)
|
||||
if (value) el.setAttribute(attr, value)
|
||||
}
|
||||
|
||||
// process child elements recursively
|
||||
const childDef = opts === 'self' ? def : opts
|
||||
let child = node.firstChild
|
||||
while (child) {
|
||||
const childEl = this.convert(child, childDef)
|
||||
if (childEl) el.append(childEl)
|
||||
child = child.nextSibling
|
||||
}
|
||||
return el
|
||||
}
|
||||
}
|
||||
|
||||
const parseXML = async blob => {
|
||||
const buffer = await blob.arrayBuffer()
|
||||
const str = new TextDecoder('utf-8').decode(buffer)
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(str, MIME.XML)
|
||||
const encoding = doc.xmlEncoding
|
||||
// `Document.xmlEncoding` is deprecated, and already removed in Firefox
|
||||
// so parse the XML declaration manually
|
||||
|| str.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1]
|
||||
if (encoding && encoding.toLowerCase() !== 'utf-8') {
|
||||
const str = new TextDecoder(encoding).decode(buffer)
|
||||
return parser.parseFromString(str, MIME.XML)
|
||||
}
|
||||
return doc
|
||||
}
|
||||
|
||||
const style = URL.createObjectURL(new Blob([`
|
||||
@namespace epub "http://www.idpf.org/2007/ops";
|
||||
body > img, section > img {
|
||||
display: block;
|
||||
margin: auto;
|
||||
}
|
||||
.title h1 {
|
||||
text-align: center;
|
||||
}
|
||||
body > section > .title, body.notesBodyType > .title {
|
||||
margin: 3em 0;
|
||||
}
|
||||
body.notesBodyType > section .title h1 {
|
||||
text-align: start;
|
||||
}
|
||||
body.notesBodyType > section .title {
|
||||
margin: 1em 0;
|
||||
}
|
||||
p {
|
||||
text-indent: 1em;
|
||||
margin: 0;
|
||||
}
|
||||
:not(p) + p, p:first-child {
|
||||
text-indent: 0;
|
||||
}
|
||||
.poem p {
|
||||
text-indent: 0;
|
||||
margin: 1em 0;
|
||||
}
|
||||
.text-author, .date {
|
||||
text-align: end;
|
||||
}
|
||||
.text-author:before {
|
||||
content: "—";
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
}
|
||||
td, th {
|
||||
padding: .25em;
|
||||
}
|
||||
a[epub|type~="noteref"] {
|
||||
font-size: .75em;
|
||||
vertical-align: super;
|
||||
}
|
||||
body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph {
|
||||
margin: 3em 0;
|
||||
}
|
||||
`], { type: 'text/css' }))
|
||||
|
||||
const template = html => `<?xml version="1.0" encoding="utf-8"?>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><link href="${style}" rel="stylesheet" type="text/css"/></head>
|
||||
<body>${html}</body>
|
||||
</html>`
|
||||
|
||||
// name of custom ID attribute for TOC items
|
||||
const dataID = 'data-foliate-id'
|
||||
|
||||
export const makeFB2 = async blob => {
|
||||
const book = {}
|
||||
const doc = await parseXML(blob)
|
||||
const converter = new FB2Converter(doc)
|
||||
|
||||
const $ = x => doc.querySelector(x)
|
||||
const $$ = x => [...doc.querySelectorAll(x)]
|
||||
const getPerson = el => {
|
||||
const nick = getElementText(el.querySelector('nickname'))
|
||||
if (nick) return nick
|
||||
const first = getElementText(el.querySelector('first-name'))
|
||||
const middle = getElementText(el.querySelector('middle-name'))
|
||||
const last = getElementText(el.querySelector('last-name'))
|
||||
const name = [first, middle, last].filter(x => x).join(' ')
|
||||
const sortAs = last
|
||||
? [last, [first, middle].filter(x => x).join(' ')].join(', ')
|
||||
: null
|
||||
return { name, sortAs }
|
||||
}
|
||||
const getDate = el => el?.getAttribute('value') ?? getElementText(el)
|
||||
const annotation = $('title-info annotation')
|
||||
book.metadata = {
|
||||
title: getElementText($('title-info book-title')),
|
||||
identifier: getElementText($('document-info id')),
|
||||
language: getElementText($('title-info lang')),
|
||||
author: $$('title-info author').map(getPerson),
|
||||
translator: $$('title-info translator').map(getPerson),
|
||||
contributor: $$('document-info author').map(getPerson)
|
||||
// techincially the program probably shouldn't get the `bkp` role
|
||||
// but it has been so used by calibre, so ¯\_(ツ)_/¯
|
||||
.concat($$('document-info program-used').map(getElementText))
|
||||
.map(x => Object.assign(typeof x === 'string' ? { name: x } : x,
|
||||
{ role: 'bkp' })),
|
||||
publisher: getElementText($('publish-info publisher')),
|
||||
published: getDate($('title-info date')),
|
||||
modified: getDate($('document-info date')),
|
||||
description: annotation ? converter.convert(annotation,
|
||||
{ annotation: ['div', SECTION] }).innerHTML : null,
|
||||
subject: $$('title-info genre').map(getElementText),
|
||||
}
|
||||
if ($('coverpage image')) {
|
||||
const src = converter.getImageSrc($('coverpage image'))
|
||||
book.getCover = () => fetch(src).then(res => res.blob())
|
||||
} else book.getCover = () => null
|
||||
|
||||
// get convert each body
|
||||
const bodyData = Array.from(doc.querySelectorAll('body'), body => {
|
||||
const converted = converter.convert(body, { body: ['body', BODY] })
|
||||
return [Array.from(converted.children, el => {
|
||||
// get list of IDs in the section
|
||||
const ids = [el, ...el.querySelectorAll('[id]')].map(el => el.id)
|
||||
return { el, ids }
|
||||
}), converted]
|
||||
})
|
||||
|
||||
const urls = []
|
||||
const sectionData = bodyData[0][0]
|
||||
// make a separate section for each section in the first body
|
||||
.map(({ el, ids }) => {
|
||||
// set up titles for TOC
|
||||
const titles = Array.from(
|
||||
el.querySelectorAll(':scope > section > .title'),
|
||||
(el, index) => {
|
||||
el.setAttribute(dataID, index)
|
||||
return { title: getElementText(el), index }
|
||||
})
|
||||
return { ids, titles, el }
|
||||
})
|
||||
// for additional bodies, only make one section for each body
|
||||
.concat(bodyData.slice(1).map(([sections, body]) => {
|
||||
const ids = sections.map(s => s.ids).flat()
|
||||
body.classList.add('notesBodyType')
|
||||
return { ids, el: body, linear: 'no' }
|
||||
}))
|
||||
.map(({ ids, titles, el, linear }) => {
|
||||
const str = template(el.outerHTML)
|
||||
const blob = new Blob([str], { type: MIME.XHTML })
|
||||
const url = URL.createObjectURL(blob)
|
||||
urls.push(url)
|
||||
const title = normalizeWhitespace(
|
||||
el.querySelector('.title, .subtitle, p')?.textContent
|
||||
?? (el.classList.contains('title') ? el.textContent : ''))
|
||||
return {
|
||||
ids, title, titles, load: () => url,
|
||||
createDocument: () => new DOMParser().parseFromString(str, MIME.XHTML),
|
||||
// doo't count image data as it'd skew the size too much
|
||||
size: blob.size - Array.from(el.querySelectorAll('[src]'),
|
||||
el => el.getAttribute('src')?.length ?? 0)
|
||||
.reduce((a, b) => a + b, 0),
|
||||
linear,
|
||||
}
|
||||
})
|
||||
|
||||
const idMap = new Map()
|
||||
book.sections = sectionData.map((section, index) => {
|
||||
const { ids, load, createDocument, size, linear } = section
|
||||
for (const id of ids) if (id) idMap.set(id, index)
|
||||
return { id: index, load, createDocument, size, linear }
|
||||
})
|
||||
|
||||
book.toc = sectionData.map(({ title, titles }, index) => {
|
||||
const id = index.toString()
|
||||
return {
|
||||
label: title,
|
||||
href: id,
|
||||
subitems: titles?.length ? titles.map(({ title, index }) => ({
|
||||
label: title,
|
||||
href: `${id}#${index}`,
|
||||
})) : null,
|
||||
}
|
||||
}).filter(item => item)
|
||||
|
||||
book.resolveHref = href => {
|
||||
const [a, b] = href.split('#')
|
||||
return a
|
||||
// the link is from the TOC
|
||||
? { index: Number(a), anchor: doc => doc.querySelector(`[${dataID}="${b}"]`) }
|
||||
// link from within the page
|
||||
: { index: idMap.get(b), anchor: doc => doc.getElementById(b) }
|
||||
}
|
||||
book.splitTOCHref = href => href?.split('#')?.map(x => Number(x)) ?? []
|
||||
book.getTOCFragment = (doc, id) => doc.querySelector(`[${dataID}="${id}"]`)
|
||||
|
||||
book.destroy = () => {
|
||||
for (const url of urls) URL.revokeObjectURL(url)
|
||||
}
|
||||
return book
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
const parseViewport = str => str
|
||||
?.split(/[,;\s]/) // NOTE: technically, only the comma is valid
|
||||
?.filter(x => x)
|
||||
?.map(x => x.split('=').map(x => x.trim()))
|
||||
|
||||
const getViewport = (doc, viewport) => {
|
||||
// use `viewBox` for SVG
|
||||
if (doc.documentElement.localName === 'svg') {
|
||||
const [, , width, height] = doc.documentElement
|
||||
.getAttribute('viewBox')?.split(/\s/) ?? []
|
||||
return { width, height }
|
||||
}
|
||||
|
||||
// get `viewport` `meta` element
|
||||
const meta = parseViewport(doc.querySelector('meta[name="viewport"]')
|
||||
?.getAttribute('content'))
|
||||
if (meta) return Object.fromEntries(meta)
|
||||
|
||||
// fallback to book's viewport
|
||||
if (typeof viewport === 'string') return parseViewport(viewport)
|
||||
if (viewport?.width && viewport.height) return viewport
|
||||
|
||||
// if no viewport (possibly with image directly in spine), get image size
|
||||
const img = doc.querySelector('img')
|
||||
if (img) return { width: img.naturalWidth, height: img.naturalHeight }
|
||||
|
||||
// just show *something*, i guess...
|
||||
console.warn(new Error('Missing viewport properties'))
|
||||
return { width: 1000, height: 2000 }
|
||||
}
|
||||
|
||||
export class FixedLayout extends HTMLElement {
|
||||
static observedAttributes = ['zoom']
|
||||
#root = this.attachShadow({ mode: 'closed' })
|
||||
#observer = new ResizeObserver(() => this.#render())
|
||||
#spreads
|
||||
#index = -1
|
||||
defaultViewport
|
||||
spread
|
||||
#portrait = false
|
||||
#left
|
||||
#right
|
||||
#center
|
||||
#side
|
||||
#zoom
|
||||
constructor() {
|
||||
super()
|
||||
|
||||
const sheet = new CSSStyleSheet()
|
||||
this.#root.adoptedStyleSheets = [sheet]
|
||||
sheet.replaceSync(`:host {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
overflow: auto;
|
||||
}`)
|
||||
|
||||
this.#observer.observe(this)
|
||||
}
|
||||
attributeChangedCallback(name, _, value) {
|
||||
switch (name) {
|
||||
case 'zoom':
|
||||
this.#zoom = value !== 'fit-width' && value !== 'fit-page'
|
||||
? parseFloat(value) : value
|
||||
this.#render()
|
||||
break
|
||||
}
|
||||
}
|
||||
async #createFrame({ index, src: srcOption }) {
|
||||
const srcOptionIsString = typeof srcOption === 'string'
|
||||
const src = srcOptionIsString ? srcOption : srcOption?.src
|
||||
const onZoom = srcOptionIsString ? null : srcOption?.onZoom
|
||||
const element = document.createElement('div')
|
||||
element.setAttribute('dir', 'ltr')
|
||||
const iframe = document.createElement('iframe')
|
||||
element.append(iframe)
|
||||
Object.assign(iframe.style, {
|
||||
border: '0',
|
||||
display: 'none',
|
||||
overflow: 'hidden',
|
||||
})
|
||||
// `allow-scripts` is needed for events because of WebKit bug
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=218086
|
||||
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts')
|
||||
iframe.setAttribute('scrolling', 'no')
|
||||
iframe.setAttribute('part', 'filter')
|
||||
this.#root.append(element)
|
||||
if (!src) return { blank: true, element, iframe }
|
||||
return new Promise(resolve => {
|
||||
iframe.addEventListener('load', () => {
|
||||
const doc = iframe.contentDocument
|
||||
this.dispatchEvent(new CustomEvent('load', { detail: { doc, index } }))
|
||||
const { width, height } = getViewport(doc, this.defaultViewport)
|
||||
resolve({
|
||||
element, iframe,
|
||||
width: parseFloat(width),
|
||||
height: parseFloat(height),
|
||||
onZoom,
|
||||
})
|
||||
}, { once: true })
|
||||
iframe.src = src
|
||||
})
|
||||
}
|
||||
#render(side = this.#side) {
|
||||
if (!side) return
|
||||
const left = this.#left ?? {}
|
||||
const right = this.#center ?? this.#right ?? {}
|
||||
const target = side === 'left' ? left : right
|
||||
const { width, height } = this.getBoundingClientRect()
|
||||
const portrait = this.spread !== 'both' && this.spread !== 'portrait'
|
||||
&& height > width
|
||||
this.#portrait = portrait
|
||||
const blankWidth = left.width ?? right.width ?? 0
|
||||
const blankHeight = left.height ?? right.height ?? 0
|
||||
|
||||
const scale = typeof this.#zoom === 'number' && !isNaN(this.#zoom)
|
||||
? this.#zoom
|
||||
: (this.#zoom === 'fit-width'
|
||||
? (portrait || this.#center
|
||||
? width / (target.width ?? blankWidth)
|
||||
: width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)))
|
||||
: (portrait || this.#center
|
||||
? Math.min(
|
||||
width / (target.width ?? blankWidth),
|
||||
height / (target.height ?? blankHeight))
|
||||
: Math.min(
|
||||
width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)),
|
||||
height / Math.max(
|
||||
left.height ?? blankHeight,
|
||||
right.height ?? blankHeight)))
|
||||
) || 1
|
||||
|
||||
const transform = frame => {
|
||||
let { element, iframe, width, height, blank, onZoom } = frame
|
||||
if (!iframe) return
|
||||
if (onZoom) onZoom({ doc: frame.iframe.contentDocument, scale })
|
||||
const iframeScale = onZoom ? scale : 1
|
||||
Object.assign(iframe.style, {
|
||||
width: `${width * iframeScale}px`,
|
||||
height: `${height * iframeScale}px`,
|
||||
transform: onZoom ? 'none' : `scale(${scale})`,
|
||||
transformOrigin: 'top left',
|
||||
display: blank ? 'none' : 'block',
|
||||
})
|
||||
Object.assign(element.style, {
|
||||
width: `${(width ?? blankWidth) * scale}px`,
|
||||
height: `${(height ?? blankHeight) * scale}px`,
|
||||
overflow: 'hidden',
|
||||
display: 'block',
|
||||
flexShrink: '0',
|
||||
marginBlock: 'auto',
|
||||
})
|
||||
if (portrait && frame !== target) {
|
||||
element.style.display = 'none'
|
||||
}
|
||||
}
|
||||
if (this.#center) {
|
||||
transform(this.#center)
|
||||
} else {
|
||||
transform(left)
|
||||
transform(right)
|
||||
}
|
||||
}
|
||||
async #showSpread({ left, right, center, side }) {
|
||||
this.#root.replaceChildren()
|
||||
this.#left = null
|
||||
this.#right = null
|
||||
this.#center = null
|
||||
if (center) {
|
||||
this.#center = await this.#createFrame(center)
|
||||
this.#side = 'center'
|
||||
this.#render()
|
||||
} else {
|
||||
this.#left = await this.#createFrame(left)
|
||||
this.#right = await this.#createFrame(right)
|
||||
this.#side = this.#left.blank ? 'right'
|
||||
: this.#right.blank ? 'left' : side
|
||||
this.#render()
|
||||
}
|
||||
}
|
||||
#goLeft() {
|
||||
if (this.#center || this.#left?.blank) return
|
||||
if (this.#portrait && this.#left?.element?.style?.display === 'none') {
|
||||
this.#side = 'left'
|
||||
this.#render()
|
||||
this.#reportLocation('page')
|
||||
return true
|
||||
}
|
||||
}
|
||||
#goRight() {
|
||||
if (this.#center || this.#right?.blank) return
|
||||
if (this.#portrait && this.#right?.element?.style?.display === 'none') {
|
||||
this.#side = 'right'
|
||||
this.#render()
|
||||
this.#reportLocation('page')
|
||||
return true
|
||||
}
|
||||
}
|
||||
open(book) {
|
||||
this.book = book
|
||||
const { rendition } = book
|
||||
this.spread = rendition?.spread
|
||||
this.defaultViewport = rendition?.viewport
|
||||
|
||||
const rtl = book.dir === 'rtl'
|
||||
const ltr = !rtl
|
||||
this.rtl = rtl
|
||||
|
||||
if (rendition?.spread === 'none')
|
||||
this.#spreads = book.sections.map(section => ({ center: section }))
|
||||
else this.#spreads = book.sections.reduce((arr, section, i) => {
|
||||
const last = arr[arr.length - 1]
|
||||
const { pageSpread } = section
|
||||
const newSpread = () => {
|
||||
const spread = {}
|
||||
arr.push(spread)
|
||||
return spread
|
||||
}
|
||||
if (pageSpread === 'center') {
|
||||
const spread = last.left || last.right ? newSpread() : last
|
||||
spread.center = section
|
||||
}
|
||||
else if (pageSpread === 'left') {
|
||||
const spread = last.center || last.left || ltr && i ? newSpread() : last
|
||||
spread.left = section
|
||||
}
|
||||
else if (pageSpread === 'right') {
|
||||
const spread = last.center || last.right || rtl && i ? newSpread() : last
|
||||
spread.right = section
|
||||
}
|
||||
else if (ltr) {
|
||||
if (last.center || last.right) newSpread().left = section
|
||||
else if (last.left || !i) last.right = section
|
||||
else last.left = section
|
||||
}
|
||||
else {
|
||||
if (last.center || last.left) newSpread().right = section
|
||||
else if (last.right || !i) last.left = section
|
||||
else last.right = section
|
||||
}
|
||||
return arr
|
||||
}, [{}])
|
||||
}
|
||||
get index() {
|
||||
const spread = this.#spreads[this.#index]
|
||||
const section = spread?.center ?? (this.#side === 'left'
|
||||
? spread.left ?? spread.right : spread.right ?? spread.left)
|
||||
return this.book.sections.indexOf(section)
|
||||
}
|
||||
#reportLocation(reason) {
|
||||
this.dispatchEvent(new CustomEvent('relocate', { detail:
|
||||
{ reason, range: null, index: this.index, fraction: 0, size: 1 } }))
|
||||
}
|
||||
getSpreadOf(section) {
|
||||
const spreads = this.#spreads
|
||||
for (let index = 0; index < spreads.length; index++) {
|
||||
const { left, right, center } = spreads[index]
|
||||
if (left === section) return { index, side: 'left' }
|
||||
if (right === section) return { index, side: 'right' }
|
||||
if (center === section) return { index, side: 'center' }
|
||||
}
|
||||
}
|
||||
async goToSpread(index, side, reason) {
|
||||
if (index < 0 || index > this.#spreads.length - 1) return
|
||||
if (index === this.#index) {
|
||||
this.#render(side)
|
||||
return
|
||||
}
|
||||
this.#index = index
|
||||
const spread = this.#spreads[index]
|
||||
if (spread.center) {
|
||||
const index = this.book.sections.indexOf(spread.center)
|
||||
const src = await spread.center?.load?.()
|
||||
await this.#showSpread({ center: { index, src } })
|
||||
} else {
|
||||
const indexL = this.book.sections.indexOf(spread.left)
|
||||
const indexR = this.book.sections.indexOf(spread.right)
|
||||
const srcL = await spread.left?.load?.()
|
||||
const srcR = await spread.right?.load?.()
|
||||
const left = { index: indexL, src: srcL }
|
||||
const right = { index: indexR, src: srcR }
|
||||
await this.#showSpread({ left, right, side })
|
||||
}
|
||||
this.#reportLocation(reason)
|
||||
}
|
||||
async select(target) {
|
||||
await this.goTo(target)
|
||||
// TODO
|
||||
}
|
||||
async goTo(target) {
|
||||
const { book } = this
|
||||
const resolved = await target
|
||||
const section = book.sections[resolved.index]
|
||||
if (!section) return
|
||||
const { index, side } = this.getSpreadOf(section)
|
||||
await this.goToSpread(index, side)
|
||||
}
|
||||
async next() {
|
||||
const s = this.rtl ? this.#goLeft() : this.#goRight()
|
||||
if (!s) return this.goToSpread(this.#index + 1, this.rtl ? 'right' : 'left', 'page')
|
||||
}
|
||||
async prev() {
|
||||
const s = this.rtl ? this.#goRight() : this.#goLeft()
|
||||
if (!s) return this.goToSpread(this.#index - 1, this.rtl ? 'left' : 'right', 'page')
|
||||
}
|
||||
getContents() {
|
||||
return Array.from(this.#root.querySelectorAll('iframe'), frame => ({
|
||||
doc: frame.contentDocument,
|
||||
// TODO: index, overlayer
|
||||
}))
|
||||
}
|
||||
destroy() {
|
||||
this.#observer.unobserve(this)
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('foliate-fxl', FixedLayout)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,175 @@
|
||||
const createSVGElement = tag =>
|
||||
document.createElementNS('http://www.w3.org/2000/svg', tag)
|
||||
|
||||
export class Overlayer {
|
||||
#svg = createSVGElement('svg')
|
||||
#map = new Map()
|
||||
constructor() {
|
||||
Object.assign(this.#svg.style, {
|
||||
position: 'absolute', top: '0', left: '0',
|
||||
width: '100%', height: '100%',
|
||||
pointerEvents: 'none',
|
||||
})
|
||||
}
|
||||
get element() {
|
||||
return this.#svg
|
||||
}
|
||||
add(key, range, draw, options) {
|
||||
if (this.#map.has(key)) this.remove(key)
|
||||
if (typeof range === 'function') range = range(this.#svg.getRootNode())
|
||||
const rects = range.getClientRects()
|
||||
const element = draw(rects, options)
|
||||
this.#svg.append(element)
|
||||
this.#map.set(key, { range, draw, options, element, rects })
|
||||
}
|
||||
remove(key) {
|
||||
if (!this.#map.has(key)) return
|
||||
this.#svg.removeChild(this.#map.get(key).element)
|
||||
this.#map.delete(key)
|
||||
}
|
||||
redraw() {
|
||||
for (const obj of this.#map.values()) {
|
||||
const { range, draw, options, element } = obj
|
||||
this.#svg.removeChild(element)
|
||||
const rects = range.getClientRects()
|
||||
const el = draw(rects, options)
|
||||
this.#svg.append(el)
|
||||
obj.element = el
|
||||
obj.rects = rects
|
||||
}
|
||||
}
|
||||
hitTest({ x, y }) {
|
||||
const arr = Array.from(this.#map.entries())
|
||||
// loop in reverse to hit more recently added items first
|
||||
for (let i = arr.length - 1; i >= 0; i--) {
|
||||
const [key, obj] = arr[i]
|
||||
for (const { left, top, right, bottom } of obj.rects)
|
||||
if (top <= y && left <= x && bottom > y && right > x)
|
||||
return [key, obj.range]
|
||||
}
|
||||
return []
|
||||
}
|
||||
static underline(rects, options = {}) {
|
||||
const { color = 'red', width: strokeWidth = 2, writingMode } = options
|
||||
const g = createSVGElement('g')
|
||||
g.setAttribute('fill', color)
|
||||
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
|
||||
for (const { right, top, height } of rects) {
|
||||
const el = createSVGElement('rect')
|
||||
el.setAttribute('x', right - strokeWidth)
|
||||
el.setAttribute('y', top)
|
||||
el.setAttribute('height', height)
|
||||
el.setAttribute('width', strokeWidth)
|
||||
g.append(el)
|
||||
}
|
||||
else for (const { left, bottom, width } of rects) {
|
||||
const el = createSVGElement('rect')
|
||||
el.setAttribute('x', left)
|
||||
el.setAttribute('y', bottom - strokeWidth)
|
||||
el.setAttribute('height', strokeWidth)
|
||||
el.setAttribute('width', width)
|
||||
g.append(el)
|
||||
}
|
||||
return g
|
||||
}
|
||||
static strikethrough(rects, options = {}) {
|
||||
const { color = 'red', width: strokeWidth = 2, writingMode } = options
|
||||
const g = createSVGElement('g')
|
||||
g.setAttribute('fill', color)
|
||||
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
|
||||
for (const { right, left, top, height } of rects) {
|
||||
const el = createSVGElement('rect')
|
||||
el.setAttribute('x', (right + left) / 2)
|
||||
el.setAttribute('y', top)
|
||||
el.setAttribute('height', height)
|
||||
el.setAttribute('width', strokeWidth)
|
||||
g.append(el)
|
||||
}
|
||||
else for (const { left, top, bottom, width } of rects) {
|
||||
const el = createSVGElement('rect')
|
||||
el.setAttribute('x', left)
|
||||
el.setAttribute('y', (top + bottom) / 2)
|
||||
el.setAttribute('height', strokeWidth)
|
||||
el.setAttribute('width', width)
|
||||
g.append(el)
|
||||
}
|
||||
return g
|
||||
}
|
||||
static squiggly(rects, options = {}) {
|
||||
const { color = 'red', width: strokeWidth = 2, writingMode } = options
|
||||
const g = createSVGElement('g')
|
||||
g.setAttribute('fill', 'none')
|
||||
g.setAttribute('stroke', color)
|
||||
g.setAttribute('stroke-width', strokeWidth)
|
||||
const block = strokeWidth * 1.5
|
||||
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
|
||||
for (const { right, top, height } of rects) {
|
||||
const el = createSVGElement('path')
|
||||
const n = Math.round(height / block / 1.5)
|
||||
const inline = height / n
|
||||
const ls = Array.from({ length: n },
|
||||
(_, i) => `l${i % 2 ? -block : block} ${inline}`).join('')
|
||||
el.setAttribute('d', `M${right} ${top}${ls}`)
|
||||
g.append(el)
|
||||
}
|
||||
else for (const { left, bottom, width } of rects) {
|
||||
const el = createSVGElement('path')
|
||||
const n = Math.round(width / block / 1.5)
|
||||
const inline = width / n
|
||||
const ls = Array.from({ length: n },
|
||||
(_, i) => `l${inline} ${i % 2 ? block : -block}`).join('')
|
||||
el.setAttribute('d', `M${left} ${bottom}${ls}`)
|
||||
g.append(el)
|
||||
}
|
||||
return g
|
||||
}
|
||||
static highlight(rects, options = {}) {
|
||||
const { color = 'red' } = options
|
||||
const g = createSVGElement('g')
|
||||
g.setAttribute('fill', color)
|
||||
g.style.opacity = 'var(--overlayer-highlight-opacity, .3)'
|
||||
g.style.mixBlendMode = 'var(--overlayer-highlight-blend-mode, normal)'
|
||||
for (const { left, top, height, width } of rects) {
|
||||
const el = createSVGElement('rect')
|
||||
el.setAttribute('x', left)
|
||||
el.setAttribute('y', top)
|
||||
el.setAttribute('height', height)
|
||||
el.setAttribute('width', width)
|
||||
g.append(el)
|
||||
}
|
||||
return g
|
||||
}
|
||||
static outline(rects, options = {}) {
|
||||
const { color = 'red', width: strokeWidth = 3, radius = 3 } = options
|
||||
const g = createSVGElement('g')
|
||||
g.setAttribute('fill', 'none')
|
||||
g.setAttribute('stroke', color)
|
||||
g.setAttribute('stroke-width', strokeWidth)
|
||||
for (const { left, top, height, width } of rects) {
|
||||
const el = createSVGElement('rect')
|
||||
el.setAttribute('x', left)
|
||||
el.setAttribute('y', top)
|
||||
el.setAttribute('height', height)
|
||||
el.setAttribute('width', width)
|
||||
el.setAttribute('rx', radius)
|
||||
g.append(el)
|
||||
}
|
||||
return g
|
||||
}
|
||||
// make an exact copy of an image in the overlay
|
||||
// one can then apply filters to the entire element, without affecting them;
|
||||
// it's a bit silly and probably better to just invert images twice
|
||||
// (though the color will be off in that case if you do heu-rotate)
|
||||
static copyImage([rect], options = {}) {
|
||||
const { src } = options
|
||||
const image = createSVGElement('image')
|
||||
const { left, top, height, width } = rect
|
||||
image.setAttribute('href', src)
|
||||
image.setAttribute('x', left)
|
||||
image.setAttribute('y', top)
|
||||
image.setAttribute('height', height)
|
||||
image.setAttribute('width', width)
|
||||
return image
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user