From e5b1d33bf7406b950d54978ae4078f3d237fb674 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sat, 17 Jan 2026 22:36:00 -0700 Subject: [PATCH] Add support for annotations and book notes in the new ebook reader (#2313) Co-authored-by: acx10 --- .../controller/AnnotationController.java | 67 +++ .../controller/BookNotesV2Controller.java | 67 +++ .../booklore/mapper/AnnotationMapper.java | 14 + .../booklore/mapper/BookNoteV2Mapper.java | 14 + .../booklore/model/dto/Annotation.java | 26 + .../booklore/model/dto/BookNoteV2.java | 25 + .../model/dto/CreateAnnotationRequest.java | 40 ++ .../model/dto/CreateBookNoteV2Request.java | 36 ++ .../model/dto/UpdateAnnotationRequest.java | 24 + .../model/dto/UpdateBookNoteV2Request.java | 23 + .../model/entity/AnnotationEntity.java | 66 +++ .../model/entity/BookNoteV2Entity.java | 63 ++ .../repository/AnnotationRepository.java | 34 ++ .../repository/BookNoteV2Repository.java | 34 ++ .../service/book/AnnotationService.java | 122 ++++ .../service/book/BookNoteV2Service.java | 120 ++++ .../V95__Create_annotations_table.sql | 27 + .../V96__Create_book_notes_v2_table.sql | 26 + .../controller/BookNotesV2ControllerTest.java | 231 ++++++++ .../service/BookNoteV2ServiceTest.java | 381 ++++++++++++ .../event.service.ts} | 266 ++++----- .../loader.service.ts} | 0 .../style.service.ts} | 10 +- .../ebook-reader/core/view-manager.service.ts | 231 ++++++++ .../metadata-dialog.component.html} | 0 .../metadata-dialog.component.scss} | 124 ++-- .../metadata-dialog.component.ts} | 8 +- .../dialogs/note-dialog.component.html | 51 ++ .../dialogs/note-dialog.component.scss | 261 +++++++++ .../dialogs/note-dialog.component.ts | 77 +++ .../settings-dialog.component.html} | 16 + .../settings-dialog.component.scss} | 453 ++++++-------- .../settings-dialog.component.ts} | 41 +- .../ebook-reader/ebook-reader.component.html | 76 +-- .../ebook-reader/ebook-reader.component.scss | 11 + .../ebook-reader/ebook-reader.component.ts | 398 +++++-------- .../annotation-renderer.service.ts | 138 +++++ .../annotations/annotation.service.ts | 130 +++++ .../bookmarks/bookmark.service.ts} | 3 +- .../fonts/custom-font.service.ts} | 4 +- .../features/notes/note.service.ts | 168 ++++++ .../features/selection/selection.service.ts | 266 +++++++++ .../features/readers/ebook-reader/index.ts | 35 ++ .../footer/footer.component.html} | 31 +- .../layout/footer/footer.component.scss | 359 ++++++++++++ .../footer/footer.component.ts} | 27 +- .../layout/header/header.component.html | 18 + .../header/header.component.scss} | 0 .../layout/header/header.component.ts | 58 ++ .../layout/header/header.service.ts | 134 +++++ .../header/quick-settings.component.html | 53 ++ .../header/quick-settings.component.scss | 260 +++++++++ .../layout/header/quick-settings.component.ts | 84 +++ .../layout/panel/panel.component.html | 171 ++++++ .../layout/panel/panel.component.scss | 524 +++++++++++++++++ .../layout/panel/panel.component.ts | 131 +++++ .../layout/panel/panel.service.ts | 204 +++++++ .../layout/sidebar/sidebar.component.html | 150 +++++ .../layout/sidebar/sidebar.component.scss | 552 ++++++++++++++++++ .../layout/sidebar/sidebar.component.ts | 122 ++++ .../layout/sidebar/sidebar.service.ts | 284 +++++++++ .../header/reader-header.component.html | 19 - .../header/reader-header.component.ts | 32 - .../navbar/reader-navbar.component.scss | 301 ---------- .../sidebar/reader-sidebar.component.html | 104 ---- .../sidebar/reader-sidebar.component.scss | 416 ------------- .../sidebar/reader-sidebar.component.ts | 127 ---- .../header-footer.util.ts} | 2 +- .../ebook-reader/shared/icon.component.ts | 169 ++++++ .../shared/selection-popup.component.html | 71 +++ .../shared/selection-popup.component.scss | 233 ++++++++ .../shared/selection-popup.component.ts | 147 +++++ .../visibility.util.ts} | 4 +- .../ebook-reader/state/progress.service.ts | 169 ++++++ .../reader-state.service.ts | 4 +- .../themes.constant.ts} | 0 .../epub-reader-preferences-component.ts | 2 +- .../app/shared/service/annotation.service.ts | 61 ++ .../shared/service/book-note-v2.service.ts | 57 ++ 79 files changed, 7481 insertions(+), 1806 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/AnnotationController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/BookNotesV2Controller.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/mapper/AnnotationMapper.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookNoteV2Mapper.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Annotation.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookNoteV2.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateAnnotationRequest.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookNoteV2Request.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateAnnotationRequest.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateBookNoteV2Request.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/entity/AnnotationEntity.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookNoteV2Entity.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/AnnotationRepository.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/BookNoteV2Repository.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/book/AnnotationService.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookNoteV2Service.java create mode 100644 booklore-api/src/main/resources/db/migration/V95__Create_annotations_table.sql create mode 100644 booklore-api/src/main/resources/db/migration/V96__Create_book_notes_v2_table.sql create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/controller/BookNotesV2ControllerTest.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/BookNoteV2ServiceTest.java rename booklore-ui/src/app/features/readers/ebook-reader/{services/reader-view-manager.service.ts => core/event.service.ts} (54%) rename booklore-ui/src/app/features/readers/ebook-reader/{services/reader-loader.service.ts => core/loader.service.ts} (100%) rename booklore-ui/src/app/features/readers/ebook-reader/{services/reader-style.service.ts => core/style.service.ts} (95%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/sidebar/reader-book-metadata-dialog.component.html => dialogs/metadata-dialog.component.html} (100%) rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/sidebar/reader-book-metadata-dialog.component.scss => dialogs/metadata-dialog.component.scss} (58%) rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/sidebar/reader-book-metadata-dialog.component.ts => dialogs/metadata-dialog.component.ts} (83%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.html create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.scss create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.ts rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/header/reader-settings-dialog.component.html => dialogs/settings-dialog.component.html} (91%) rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/header/reader-settings-dialog.component.scss => dialogs/settings-dialog.component.scss} (56%) rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/header/reader-settings-dialog.component.ts => dialogs/settings-dialog.component.ts} (75%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation-renderer.service.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation.service.ts rename booklore-ui/src/app/features/readers/ebook-reader/{services/reader-bookmark.service.ts => features/bookmarks/bookmark.service.ts} (91%) rename booklore-ui/src/app/features/readers/ebook-reader/{services/epub-custom-font.service.ts => features/fonts/custom-font.service.ts} (95%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/features/notes/note.service.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/features/selection/selection.service.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/index.ts rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/navbar/reader-navbar.component.html => layout/footer/footer.component.html} (69%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.scss rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/navbar/reader-navbar.component.ts => layout/footer/footer.component.ts} (82%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html rename booklore-ui/src/app/features/readers/ebook-reader/{reader-layout/header/reader-header.component.scss => layout/header/header.component.scss} (100%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.html create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.scss create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.html create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.scss create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.service.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.html create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.scss create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts delete mode 100644 booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.html delete mode 100644 booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.ts delete mode 100644 booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.scss delete mode 100644 booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.html delete mode 100644 booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.scss delete mode 100644 booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.ts rename booklore-ui/src/app/features/readers/ebook-reader/{utils/reader-header-footer.util.ts => shared/header-footer.util.ts} (99%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/shared/icon.component.ts create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.html create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.scss create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.ts rename booklore-ui/src/app/features/readers/ebook-reader/{utils/reader-header-footer-visibility.util.ts => shared/visibility.util.ts} (96%) create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/state/progress.service.ts rename booklore-ui/src/app/features/readers/ebook-reader/{services => state}/reader-state.service.ts (98%) rename booklore-ui/src/app/features/readers/ebook-reader/{services/reader-themes.ts => state/themes.constant.ts} (100%) create mode 100644 booklore-ui/src/app/shared/service/annotation.service.ts create mode 100644 booklore-ui/src/app/shared/service/book-note-v2.service.ts diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/AnnotationController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/AnnotationController.java new file mode 100644 index 000000000..3f99c4d4e --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/AnnotationController.java @@ -0,0 +1,67 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.model.dto.Annotation; +import com.adityachandel.booklore.model.dto.CreateAnnotationRequest; +import com.adityachandel.booklore.model.dto.UpdateAnnotationRequest; +import com.adityachandel.booklore.service.book.AnnotationService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v1/annotations") +@Tag(name = "Annotations", description = "Endpoints for managing book annotations (highlights, underlines, etc.)") +public class AnnotationController { + + private final AnnotationService annotationService; + + @Operation(summary = "Get annotations for a book", description = "Retrieve all annotations for a specific book.") + @ApiResponse(responseCode = "200", description = "Annotations returned successfully") + @GetMapping("/book/{bookId}") + public List getAnnotationsForBook( + @Parameter(description = "ID of the book") @PathVariable Long bookId) { + return annotationService.getAnnotationsForBook(bookId); + } + + @Operation(summary = "Get a specific annotation", description = "Retrieve a specific annotation by its ID.") + @ApiResponse(responseCode = "200", description = "Annotation returned successfully") + @GetMapping("/{annotationId}") + public Annotation getAnnotationById( + @Parameter(description = "ID of the annotation") @PathVariable Long annotationId) { + return annotationService.getAnnotationById(annotationId); + } + + @Operation(summary = "Create an annotation", description = "Create a new annotation (highlight, underline, etc.) for a book.") + @ApiResponse(responseCode = "200", description = "Annotation created successfully") + @PostMapping + public Annotation createAnnotation( + @Parameter(description = "Annotation creation request") @Valid @RequestBody CreateAnnotationRequest request) { + return annotationService.createAnnotation(request); + } + + @Operation(summary = "Update an annotation", description = "Update an existing annotation's properties (color, style, note).") + @ApiResponse(responseCode = "200", description = "Annotation updated successfully") + @PutMapping("/{annotationId}") + public Annotation updateAnnotation( + @Parameter(description = "ID of the annotation to update") @PathVariable Long annotationId, + @Parameter(description = "Annotation update request") @Valid @RequestBody UpdateAnnotationRequest request) { + return annotationService.updateAnnotation(annotationId, request); + } + + @Operation(summary = "Delete an annotation", description = "Delete a specific annotation by its ID.") + @ApiResponse(responseCode = "204", description = "Annotation deleted successfully") + @DeleteMapping("/{annotationId}") + public ResponseEntity deleteAnnotation( + @Parameter(description = "ID of the annotation to delete") @PathVariable Long annotationId) { + annotationService.deleteAnnotation(annotationId); + return ResponseEntity.noContent().build(); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookNotesV2Controller.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookNotesV2Controller.java new file mode 100644 index 000000000..99d3a45f4 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookNotesV2Controller.java @@ -0,0 +1,67 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.model.dto.BookNoteV2; +import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request; +import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request; +import com.adityachandel.booklore.service.book.BookNoteV2Service; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/api/v2/book-notes") +@Tag(name = "Book Notes V2", description = "Endpoints for managing CFI-based book notes with text selection context") +public class BookNotesV2Controller { + + private final BookNoteV2Service bookNoteV2Service; + + @Operation(summary = "Get notes for a book", description = "Retrieve all notes for a specific book.") + @ApiResponse(responseCode = "200", description = "Notes returned successfully") + @GetMapping("/book/{bookId}") + public List getNotesForBook( + @Parameter(description = "ID of the book") @PathVariable Long bookId) { + return bookNoteV2Service.getNotesForBook(bookId); + } + + @Operation(summary = "Get a specific note", description = "Retrieve a specific note by its ID.") + @ApiResponse(responseCode = "200", description = "Note returned successfully") + @GetMapping("/{noteId}") + public BookNoteV2 getNoteById( + @Parameter(description = "ID of the note") @PathVariable Long noteId) { + return bookNoteV2Service.getNoteById(noteId); + } + + @Operation(summary = "Create a note", description = "Create a new note at a specific location in a book.") + @ApiResponse(responseCode = "200", description = "Note created successfully") + @PostMapping + public BookNoteV2 createNote( + @Parameter(description = "Note creation request") @Valid @RequestBody CreateBookNoteV2Request request) { + return bookNoteV2Service.createNote(request); + } + + @Operation(summary = "Update a note", description = "Update an existing note's content or color.") + @ApiResponse(responseCode = "200", description = "Note updated successfully") + @PutMapping("/{noteId}") + public BookNoteV2 updateNote( + @Parameter(description = "ID of the note to update") @PathVariable Long noteId, + @Parameter(description = "Note update request") @Valid @RequestBody UpdateBookNoteV2Request request) { + return bookNoteV2Service.updateNote(noteId, request); + } + + @Operation(summary = "Delete a note", description = "Delete a specific note by its ID.") + @ApiResponse(responseCode = "204", description = "Note deleted successfully") + @DeleteMapping("/{noteId}") + public ResponseEntity deleteNote( + @Parameter(description = "ID of the note to delete") @PathVariable Long noteId) { + bookNoteV2Service.deleteNote(noteId); + return ResponseEntity.noContent().build(); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/AnnotationMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/AnnotationMapper.java new file mode 100644 index 000000000..b72e401be --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/AnnotationMapper.java @@ -0,0 +1,14 @@ +package com.adityachandel.booklore.mapper; + +import com.adityachandel.booklore.model.dto.Annotation; +import com.adityachandel.booklore.model.entity.AnnotationEntity; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring") +public interface AnnotationMapper { + + @Mapping(source = "book.id", target = "bookId") + @Mapping(source = "user.id", target = "userId") + Annotation toDto(AnnotationEntity entity); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookNoteV2Mapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookNoteV2Mapper.java new file mode 100644 index 000000000..259a40d6d --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/BookNoteV2Mapper.java @@ -0,0 +1,14 @@ +package com.adityachandel.booklore.mapper; + +import com.adityachandel.booklore.model.dto.BookNoteV2; +import com.adityachandel.booklore.model.entity.BookNoteV2Entity; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +@Mapper(componentModel = "spring") +public interface BookNoteV2Mapper { + + @Mapping(source = "book.id", target = "bookId") + @Mapping(source = "user.id", target = "userId") + BookNoteV2 toDto(BookNoteV2Entity entity); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Annotation.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Annotation.java new file mode 100644 index 000000000..3d93c6058 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Annotation.java @@ -0,0 +1,26 @@ +package com.adityachandel.booklore.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class Annotation { + private Long id; + private Long userId; + private Long bookId; + private String cfi; + private String text; + private String color; + private String style; + private String note; + private String chapterTitle; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookNoteV2.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookNoteV2.java new file mode 100644 index 000000000..faec1a6e2 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookNoteV2.java @@ -0,0 +1,25 @@ +package com.adityachandel.booklore.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class BookNoteV2 { + private Long id; + private Long userId; + private Long bookId; + private String cfi; + private String selectedText; + private String noteContent; + private String color; + private String chapterTitle; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateAnnotationRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateAnnotationRequest.java new file mode 100644 index 000000000..920d7d923 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateAnnotationRequest.java @@ -0,0 +1,40 @@ +package com.adityachandel.booklore.model.dto; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CreateAnnotationRequest { + + @NotNull(message = "Book ID is required") + private Long bookId; + + @NotEmpty(message = "CFI is required") + @Size(max = 1000, message = "CFI must not exceed 1000 characters") + private String cfi; + + @NotEmpty(message = "Text is required") + @Size(max = 5000, message = "Text must not exceed 5000 characters") + private String text; + + @Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)") + private String color; + + @Pattern(regexp = "^(highlight|underline|strikethrough|squiggly)$", message = "Style must be one of: highlight, underline, strikethrough, squiggly") + private String style; + + @Size(max = 5000, message = "Note must not exceed 5000 characters") + private String note; + + @Size(max = 500, message = "Chapter title must not exceed 500 characters") + private String chapterTitle; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookNoteV2Request.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookNoteV2Request.java new file mode 100644 index 000000000..c3c0bcc71 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CreateBookNoteV2Request.java @@ -0,0 +1,36 @@ +package com.adityachandel.booklore.model.dto; + +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CreateBookNoteV2Request { + + @NotNull(message = "Book ID is required") + private Long bookId; + + @NotEmpty(message = "CFI is required") + @Size(max = 1000, message = "CFI must not exceed 1000 characters") + private String cfi; + + @Size(max = 5000, message = "Selected text must not exceed 5000 characters") + private String selectedText; + + @NotEmpty(message = "Note content is required") + private String noteContent; + + @Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)") + private String color; + + @Size(max = 500, message = "Chapter title must not exceed 500 characters") + private String chapterTitle; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateAnnotationRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateAnnotationRequest.java new file mode 100644 index 000000000..5ce9ae0f8 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateAnnotationRequest.java @@ -0,0 +1,24 @@ +package com.adityachandel.booklore.model.dto; + +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class UpdateAnnotationRequest { + + @Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)") + private String color; + + @Pattern(regexp = "^(highlight|underline|strikethrough|squiggly)$", message = "Style must be one of: highlight, underline, strikethrough, squiggly") + private String style; + + @Size(max = 5000, message = "Note must not exceed 5000 characters") + private String note; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateBookNoteV2Request.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateBookNoteV2Request.java new file mode 100644 index 000000000..4a7de23bb --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/UpdateBookNoteV2Request.java @@ -0,0 +1,23 @@ +package com.adityachandel.booklore.model.dto; + +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class UpdateBookNoteV2Request { + + private String noteContent; + + @Pattern(regexp = "^#[0-9A-Fa-f]{6}$", message = "Color must be a valid hex color (e.g., #FFFF00)") + private String color; + + @Size(max = 500, message = "Chapter title must not exceed 500 characters") + private String chapterTitle; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/AnnotationEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/AnnotationEntity.java new file mode 100644 index 000000000..cbc98a3e7 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/AnnotationEntity.java @@ -0,0 +1,66 @@ +package com.adityachandel.booklore.model.entity; + +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "annotations") +public class AnnotationEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private BookLoreUserEntity user; + + @Column(name = "user_id", insertable = false, updatable = false) + private Long userId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "book_id", nullable = false) + private BookEntity book; + + @Column(name = "book_id", insertable = false, updatable = false) + private Long bookId; + + @Column(name = "cfi", nullable = false, length = 1000) + private String cfi; + + @Column(name = "text", nullable = false, length = 5000) + private String text; + + @Column(name = "color", length = 20) + private String color; + + @Column(name = "style", length = 50) + private String style; + + @Column(name = "note", length = 5000) + private String note; + + @Column(name = "chapter_title", length = 500) + private String chapterTitle; + + @jakarta.persistence.Version + @Column(name = "version", nullable = false) + private Long version; + + @CreationTimestamp + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @UpdateTimestamp + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookNoteV2Entity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookNoteV2Entity.java new file mode 100644 index 000000000..e89abb75f --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookNoteV2Entity.java @@ -0,0 +1,63 @@ +package com.adityachandel.booklore.model.entity; + +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "book_notes_v2") +public class BookNoteV2Entity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private BookLoreUserEntity user; + + @Column(name = "user_id", insertable = false, updatable = false) + private Long userId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "book_id", nullable = false) + private BookEntity book; + + @Column(name = "book_id", insertable = false, updatable = false) + private Long bookId; + + @Column(name = "cfi", nullable = false, length = 1000) + private String cfi; + + @Column(name = "selected_text", length = 5000) + private String selectedText; + + @Column(name = "note_content", nullable = false, columnDefinition = "TEXT") + private String noteContent; + + @Column(name = "color", length = 20) + private String color; + + @Column(name = "chapter_title", length = 500) + private String chapterTitle; + + @jakarta.persistence.Version + @Column(name = "version", nullable = false) + private Long version; + + @CreationTimestamp + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + @UpdateTimestamp + @Column(name = "updated_at", nullable = false) + private LocalDateTime updatedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/AnnotationRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/AnnotationRepository.java new file mode 100644 index 000000000..a673f69ff --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/AnnotationRepository.java @@ -0,0 +1,34 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.AnnotationEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; +import java.util.Optional; + +public interface AnnotationRepository extends JpaRepository { + + Optional findByIdAndUserId(Long id, Long userId); + + @Query("SELECT a FROM AnnotationEntity a WHERE a.bookId = :bookId AND a.userId = :userId ORDER BY a.createdAt DESC") + List findByBookIdAndUserIdOrderByCreatedAtDesc( + @Param("bookId") Long bookId, + @Param("userId") Long userId + ); + + boolean existsByCfiAndBookIdAndUserId(String cfi, Long bookId, Long userId); + + @Query("SELECT COUNT(a) > 0 FROM AnnotationEntity a WHERE a.cfi = :cfi AND a.bookId = :bookId AND a.userId = :userId AND a.id != :excludeId") + boolean existsByCfiAndBookIdAndUserIdExcludeId( + @Param("cfi") String cfi, + @Param("bookId") Long bookId, + @Param("userId") Long userId, + @Param("excludeId") Long excludeId + ); + + long countByBookIdAndUserId(Long bookId, Long userId); + + void deleteByBookIdAndUserId(Long bookId, Long userId); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookNoteV2Repository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookNoteV2Repository.java new file mode 100644 index 000000000..92f96a945 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookNoteV2Repository.java @@ -0,0 +1,34 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.BookNoteV2Entity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; +import java.util.Optional; + +public interface BookNoteV2Repository extends JpaRepository { + + Optional findByIdAndUserId(Long id, Long userId); + + @Query("SELECT n FROM BookNoteV2Entity n WHERE n.bookId = :bookId AND n.userId = :userId ORDER BY n.createdAt DESC") + List findByBookIdAndUserIdOrderByCreatedAtDesc( + @Param("bookId") Long bookId, + @Param("userId") Long userId + ); + + boolean existsByCfiAndBookIdAndUserId(String cfi, Long bookId, Long userId); + + @Query("SELECT COUNT(n) > 0 FROM BookNoteV2Entity n WHERE n.cfi = :cfi AND n.bookId = :bookId AND n.userId = :userId AND n.id != :excludeId") + boolean existsByCfiAndBookIdAndUserIdExcludeId( + @Param("cfi") String cfi, + @Param("bookId") Long bookId, + @Param("userId") Long userId, + @Param("excludeId") Long excludeId + ); + + long countByBookIdAndUserId(Long bookId, Long userId); + + void deleteByBookIdAndUserId(Long bookId, Long userId); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/AnnotationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/AnnotationService.java new file mode 100644 index 000000000..c277c2116 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/AnnotationService.java @@ -0,0 +1,122 @@ +package com.adityachandel.booklore.service.book; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.AnnotationMapper; +import com.adityachandel.booklore.model.dto.Annotation; +import com.adityachandel.booklore.model.dto.CreateAnnotationRequest; +import com.adityachandel.booklore.model.dto.UpdateAnnotationRequest; +import com.adityachandel.booklore.model.entity.AnnotationEntity; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.repository.AnnotationRepository; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.UserRepository; +import jakarta.persistence.EntityNotFoundException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +@Slf4j +public class AnnotationService { + + private final AnnotationRepository annotationRepository; + private final BookRepository bookRepository; + private final UserRepository userRepository; + private final AuthenticationService authenticationService; + private final AnnotationMapper mapper; + + @Transactional(readOnly = true) + public List getAnnotationsForBook(Long bookId) { + Long userId = getCurrentUserId(); + return annotationRepository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId) + .stream() + .map(mapper::toDto) + .toList(); + } + + @Transactional(readOnly = true) + public Annotation getAnnotationById(Long annotationId) { + return mapper.toDto(findAnnotationByIdAndUser(annotationId)); + } + + @Transactional + public Annotation createAnnotation(CreateAnnotationRequest request) { + Long userId = getCurrentUserId(); + validateNoDuplicateAnnotation(request.getCfi(), request.getBookId(), userId); + + String color = request.getColor() != null ? request.getColor() : "#FFFF00"; + String style = request.getStyle() != null ? request.getStyle() : "highlight"; + + AnnotationEntity annotation = AnnotationEntity.builder() + .cfi(request.getCfi()) + .text(request.getText()) + .color(color) + .style(style) + .note(request.getNote()) + .chapterTitle(request.getChapterTitle()) + .book(findBook(request.getBookId())) + .user(findUser(userId)) + .build(); + + log.info("Creating annotation for book {} by user {}", request.getBookId(), userId); + return mapper.toDto(annotationRepository.save(annotation)); + } + + @Transactional + public Annotation updateAnnotation(Long annotationId, UpdateAnnotationRequest request) { + AnnotationEntity annotation = findAnnotationByIdAndUser(annotationId); + + applyUpdates(annotation, request); + + log.info("Updating annotation {}", annotationId); + return mapper.toDto(annotationRepository.save(annotation)); + } + + @Transactional + public void deleteAnnotation(Long annotationId) { + AnnotationEntity annotation = findAnnotationByIdAndUser(annotationId); + log.info("Deleting annotation {}", annotationId); + annotationRepository.delete(annotation); + } + + private Long getCurrentUserId() { + return authenticationService.getAuthenticatedUser().getId(); + } + + private AnnotationEntity findAnnotationByIdAndUser(Long annotationId) { + Long userId = getCurrentUserId(); + return annotationRepository.findByIdAndUserId(annotationId, userId) + .orElseThrow(() -> new EntityNotFoundException("Annotation not found: " + annotationId)); + } + + private BookEntity findBook(Long bookId) { + return bookRepository.findById(bookId) + .orElseThrow(() -> new EntityNotFoundException("Book not found: " + bookId)); + } + + private BookLoreUserEntity findUser(Long userId) { + return userRepository.findById(userId) + .orElseThrow(() -> new EntityNotFoundException("User not found: " + userId)); + } + + private void validateNoDuplicateAnnotation(String cfi, Long bookId, Long userId) { + boolean exists = annotationRepository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId); + if (exists) { + throw new APIException("Annotation already exists at this location", HttpStatus.CONFLICT); + } + } + + private void applyUpdates(AnnotationEntity annotation, UpdateAnnotationRequest request) { + Optional.ofNullable(request.getColor()).ifPresent(annotation::setColor); + Optional.ofNullable(request.getStyle()).ifPresent(annotation::setStyle); + Optional.ofNullable(request.getNote()).ifPresent(annotation::setNote); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookNoteV2Service.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookNoteV2Service.java new file mode 100644 index 000000000..bcccc76f9 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookNoteV2Service.java @@ -0,0 +1,120 @@ +package com.adityachandel.booklore.service.book; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.BookNoteV2Mapper; +import com.adityachandel.booklore.model.dto.BookNoteV2; +import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request; +import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.BookNoteV2Entity; +import com.adityachandel.booklore.repository.BookNoteV2Repository; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.UserRepository; +import jakarta.persistence.EntityNotFoundException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +@Slf4j +public class BookNoteV2Service { + + private final BookNoteV2Repository bookNoteV2Repository; + private final BookRepository bookRepository; + private final UserRepository userRepository; + private final AuthenticationService authenticationService; + private final BookNoteV2Mapper mapper; + + @Transactional(readOnly = true) + public List getNotesForBook(Long bookId) { + Long userId = getCurrentUserId(); + return bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId) + .stream() + .map(mapper::toDto) + .toList(); + } + + @Transactional(readOnly = true) + public BookNoteV2 getNoteById(Long noteId) { + return mapper.toDto(findNoteByIdAndUser(noteId)); + } + + @Transactional + public BookNoteV2 createNote(CreateBookNoteV2Request request) { + Long userId = getCurrentUserId(); + validateNoDuplicateNote(request.getCfi(), request.getBookId(), userId); + + String color = request.getColor() != null ? request.getColor() : "#FFC107"; + + BookNoteV2Entity note = BookNoteV2Entity.builder() + .cfi(request.getCfi()) + .selectedText(request.getSelectedText()) + .noteContent(request.getNoteContent()) + .color(color) + .chapterTitle(request.getChapterTitle()) + .book(findBook(request.getBookId())) + .user(findUser(userId)) + .build(); + + log.info("Creating note for book {} by user {}", request.getBookId(), userId); + return mapper.toDto(bookNoteV2Repository.save(note)); + } + + @Transactional + public BookNoteV2 updateNote(Long noteId, UpdateBookNoteV2Request request) { + BookNoteV2Entity note = findNoteByIdAndUser(noteId); + + applyUpdates(note, request); + + log.info("Updating note {}", noteId); + return mapper.toDto(bookNoteV2Repository.save(note)); + } + + @Transactional + public void deleteNote(Long noteId) { + BookNoteV2Entity note = findNoteByIdAndUser(noteId); + log.info("Deleting note {}", noteId); + bookNoteV2Repository.delete(note); + } + + private Long getCurrentUserId() { + return authenticationService.getAuthenticatedUser().getId(); + } + + private BookNoteV2Entity findNoteByIdAndUser(Long noteId) { + Long userId = getCurrentUserId(); + return bookNoteV2Repository.findByIdAndUserId(noteId, userId) + .orElseThrow(() -> new EntityNotFoundException("Note not found: " + noteId)); + } + + private BookEntity findBook(Long bookId) { + return bookRepository.findById(bookId) + .orElseThrow(() -> new EntityNotFoundException("Book not found: " + bookId)); + } + + private BookLoreUserEntity findUser(Long userId) { + return userRepository.findById(userId) + .orElseThrow(() -> new EntityNotFoundException("User not found: " + userId)); + } + + private void validateNoDuplicateNote(String cfi, Long bookId, Long userId) { + boolean exists = bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId); + if (exists) { + throw new APIException("Note already exists at this location", HttpStatus.CONFLICT); + } + } + + private void applyUpdates(BookNoteV2Entity note, UpdateBookNoteV2Request request) { + Optional.ofNullable(request.getNoteContent()).ifPresent(note::setNoteContent); + Optional.ofNullable(request.getColor()).ifPresent(note::setColor); + Optional.ofNullable(request.getChapterTitle()).ifPresent(note::setChapterTitle); + } +} diff --git a/booklore-api/src/main/resources/db/migration/V95__Create_annotations_table.sql b/booklore-api/src/main/resources/db/migration/V95__Create_annotations_table.sql new file mode 100644 index 000000000..b6d74e540 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V95__Create_annotations_table.sql @@ -0,0 +1,27 @@ +CREATE TABLE annotations +( + id BIGINT AUTO_INCREMENT NOT NULL, + user_id BIGINT NOT NULL, + book_id BIGINT NOT NULL, + cfi VARCHAR(1000) NOT NULL, + text VARCHAR(5000) NOT NULL, + color VARCHAR(20) NULL, + style VARCHAR(50) NULL, + note VARCHAR(5000) NULL, + chapter_title VARCHAR(500) NULL, + version BIGINT NOT NULL DEFAULT 0, + created_at datetime NOT NULL, + updated_at datetime NOT NULL, + CONSTRAINT pk_annotations PRIMARY KEY (id), + CONSTRAINT uq_annotation_user_book_cfi UNIQUE (user_id, book_id, cfi) +); + +CREATE INDEX idx_annotations_user_id ON annotations (user_id); +CREATE INDEX idx_annotations_book_id ON annotations (book_id); +CREATE INDEX idx_annotations_user_book ON annotations (user_id, book_id); + +ALTER TABLE annotations + ADD CONSTRAINT fk_annotations_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE; + +ALTER TABLE annotations + ADD CONSTRAINT fk_annotations_book_id FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE; diff --git a/booklore-api/src/main/resources/db/migration/V96__Create_book_notes_v2_table.sql b/booklore-api/src/main/resources/db/migration/V96__Create_book_notes_v2_table.sql new file mode 100644 index 000000000..061a8bd63 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V96__Create_book_notes_v2_table.sql @@ -0,0 +1,26 @@ +CREATE TABLE book_notes_v2 +( + id BIGINT AUTO_INCREMENT NOT NULL, + user_id BIGINT NOT NULL, + book_id BIGINT NOT NULL, + cfi VARCHAR(1000) NOT NULL, + selected_text VARCHAR(5000) NULL, + note_content TEXT NOT NULL, + color VARCHAR(20) NULL, + chapter_title VARCHAR(500) NULL, + version BIGINT NOT NULL DEFAULT 0, + created_at datetime NOT NULL, + updated_at datetime NOT NULL, + CONSTRAINT pk_book_notes_v2 PRIMARY KEY (id), + CONSTRAINT uq_book_notes_v2_user_book_cfi UNIQUE (user_id, book_id, cfi) +); + +CREATE INDEX idx_book_notes_v2_user_id ON book_notes_v2 (user_id); +CREATE INDEX idx_book_notes_v2_book_id ON book_notes_v2 (book_id); +CREATE INDEX idx_book_notes_v2_user_book ON book_notes_v2 (user_id, book_id); + +ALTER TABLE book_notes_v2 + ADD CONSTRAINT fk_book_notes_v2_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE; + +ALTER TABLE book_notes_v2 + ADD CONSTRAINT fk_book_notes_v2_book_id FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE; diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookNotesV2ControllerTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookNotesV2ControllerTest.java new file mode 100644 index 000000000..556b7e76d --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookNotesV2ControllerTest.java @@ -0,0 +1,231 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.model.dto.BookNoteV2; +import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request; +import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request; +import com.adityachandel.booklore.service.book.BookNoteV2Service; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class BookNotesV2ControllerTest { + + @Mock + private BookNoteV2Service bookNoteV2Service; + + @InjectMocks + private BookNotesV2Controller controller; + + private final Long bookId = 1L; + private final Long noteId = 2L; + private final Long userId = 3L; + private final String cfi = "epubcfi(/6/4!/4/2/1:0)"; + private final String selectedText = "Some selected text"; + private final String noteContent = "My note content"; + private final String color = "#FFC107"; + private final String chapterTitle = "Chapter 1"; + + @Test + void getNotesForBook_returnsNotesList() { + BookNoteV2 note1 = createSampleNote(1L); + BookNoteV2 note2 = createSampleNote(2L); + List expectedNotes = List.of(note1, note2); + + when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(expectedNotes); + + List result = controller.getNotesForBook(bookId); + + assertEquals(2, result.size()); + assertEquals(1L, result.get(0).getId()); + assertEquals(2L, result.get(1).getId()); + verify(bookNoteV2Service).getNotesForBook(bookId); + } + + @Test + void getNotesForBook_returnsEmptyList_whenNoNotes() { + when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(Collections.emptyList()); + + List result = controller.getNotesForBook(bookId); + + assertTrue(result.isEmpty()); + verify(bookNoteV2Service).getNotesForBook(bookId); + } + + @Test + void getNoteById_returnsNote() { + BookNoteV2 expectedNote = createSampleNote(noteId); + + when(bookNoteV2Service.getNoteById(noteId)).thenReturn(expectedNote); + + BookNoteV2 result = controller.getNoteById(noteId); + + assertEquals(noteId, result.getId()); + assertEquals(cfi, result.getCfi()); + assertEquals(selectedText, result.getSelectedText()); + assertEquals(noteContent, result.getNoteContent()); + assertEquals(color, result.getColor()); + assertEquals(chapterTitle, result.getChapterTitle()); + verify(bookNoteV2Service).getNoteById(noteId); + } + + @Test + void createNote_createsAndReturnsNote() { + CreateBookNoteV2Request request = CreateBookNoteV2Request.builder() + .bookId(bookId) + .cfi(cfi) + .selectedText(selectedText) + .noteContent(noteContent) + .color(color) + .chapterTitle(chapterTitle) + .build(); + + BookNoteV2 expectedNote = createSampleNote(noteId); + + when(bookNoteV2Service.createNote(request)).thenReturn(expectedNote); + + BookNoteV2 result = controller.createNote(request); + + assertEquals(noteId, result.getId()); + assertEquals(cfi, result.getCfi()); + assertEquals(noteContent, result.getNoteContent()); + verify(bookNoteV2Service).createNote(request); + } + + @Test + void createNote_createsNoteWithoutOptionalFields() { + CreateBookNoteV2Request request = CreateBookNoteV2Request.builder() + .bookId(bookId) + .cfi(cfi) + .noteContent(noteContent) + .build(); + + BookNoteV2 expectedNote = BookNoteV2.builder() + .id(noteId) + .bookId(bookId) + .userId(userId) + .cfi(cfi) + .noteContent(noteContent) + .color("#FFC107") + .build(); + + when(bookNoteV2Service.createNote(request)).thenReturn(expectedNote); + + BookNoteV2 result = controller.createNote(request); + + assertEquals(noteId, result.getId()); + assertNull(result.getSelectedText()); + assertNull(result.getChapterTitle()); + verify(bookNoteV2Service).createNote(request); + } + + @Test + void updateNote_updatesAndReturnsNote() { + UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder() + .noteContent("Updated content") + .color("#00FF00") + .chapterTitle("Updated chapter") + .build(); + + BookNoteV2 expectedNote = BookNoteV2.builder() + .id(noteId) + .bookId(bookId) + .userId(userId) + .cfi(cfi) + .noteContent("Updated content") + .color("#00FF00") + .chapterTitle("Updated chapter") + .build(); + + when(bookNoteV2Service.updateNote(noteId, request)).thenReturn(expectedNote); + + BookNoteV2 result = controller.updateNote(noteId, request); + + assertEquals(noteId, result.getId()); + assertEquals("Updated content", result.getNoteContent()); + assertEquals("#00FF00", result.getColor()); + assertEquals("Updated chapter", result.getChapterTitle()); + verify(bookNoteV2Service).updateNote(noteId, request); + } + + @Test + void updateNote_updatesPartialFields() { + UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder() + .noteContent("Updated content only") + .build(); + + BookNoteV2 expectedNote = BookNoteV2.builder() + .id(noteId) + .noteContent("Updated content only") + .color(color) + .chapterTitle(chapterTitle) + .build(); + + when(bookNoteV2Service.updateNote(noteId, request)).thenReturn(expectedNote); + + BookNoteV2 result = controller.updateNote(noteId, request); + + assertEquals("Updated content only", result.getNoteContent()); + assertEquals(color, result.getColor()); + assertEquals(chapterTitle, result.getChapterTitle()); + verify(bookNoteV2Service).updateNote(noteId, request); + } + + @Test + void deleteNote_deletesNoteAndReturnsNoContent() { + doNothing().when(bookNoteV2Service).deleteNote(noteId); + + ResponseEntity response = controller.deleteNote(noteId); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + assertNull(response.getBody()); + verify(bookNoteV2Service).deleteNote(noteId); + } + + @Test + void deleteNote_callsServiceWithCorrectId() { + doNothing().when(bookNoteV2Service).deleteNote(noteId); + + controller.deleteNote(noteId); + + verify(bookNoteV2Service, times(1)).deleteNote(noteId); + } + + @Test + void getNotesForBook_delegatesToService() { + List notes = List.of(createSampleNote(1L), createSampleNote(2L), createSampleNote(3L)); + when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(notes); + + List result = controller.getNotesForBook(bookId); + + assertEquals(3, result.size()); + verify(bookNoteV2Service, times(1)).getNotesForBook(bookId); + verifyNoMoreInteractions(bookNoteV2Service); + } + + private BookNoteV2 createSampleNote(Long id) { + return BookNoteV2.builder() + .id(id) + .bookId(bookId) + .userId(userId) + .cfi(cfi) + .selectedText(selectedText) + .noteContent(noteContent) + .color(color) + .chapterTitle(chapterTitle) + .createdAt(LocalDateTime.now()) + .updatedAt(LocalDateTime.now()) + .build(); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/BookNoteV2ServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/BookNoteV2ServiceTest.java new file mode 100644 index 000000000..be9df7e1c --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/BookNoteV2ServiceTest.java @@ -0,0 +1,381 @@ +package com.adityachandel.booklore.service; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.BookNoteV2Mapper; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.BookNoteV2; +import com.adityachandel.booklore.model.dto.CreateBookNoteV2Request; +import com.adityachandel.booklore.model.dto.UpdateBookNoteV2Request; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.BookNoteV2Entity; +import com.adityachandel.booklore.repository.BookNoteV2Repository; +import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.book.BookNoteV2Service; +import jakarta.persistence.EntityNotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class BookNoteV2ServiceTest { + + private BookNoteV2Repository bookNoteV2Repository; + private BookRepository bookRepository; + private UserRepository userRepository; + private AuthenticationService authenticationService; + private BookNoteV2Mapper mapper; + private BookNoteV2Service service; + + private final Long userId = 1L; + private final Long bookId = 2L; + private final Long noteId = 3L; + private final String cfi = "epubcfi(/6/4!/4/2/1:0)"; + private final String selectedText = "Some selected text"; + private final String noteContent = "My note content"; + private final String defaultColor = "#FFC107"; + private final String customColor = "#FF5733"; + private final String chapterTitle = "Chapter 1"; + + @BeforeEach + void setUp() { + bookNoteV2Repository = mock(BookNoteV2Repository.class); + bookRepository = mock(BookRepository.class); + userRepository = mock(UserRepository.class); + authenticationService = mock(AuthenticationService.class); + mapper = mock(BookNoteV2Mapper.class); + service = new BookNoteV2Service(bookNoteV2Repository, bookRepository, userRepository, authenticationService, mapper); + + BookLoreUser user = new BookLoreUser(); + user.setId(userId); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + } + + @Test + void getNotesForBook_returnsMappedNotes() { + BookNoteV2Entity entity = BookNoteV2Entity.builder().id(noteId).cfi(cfi).build(); + BookNoteV2 dto = BookNoteV2.builder().id(noteId).cfi(cfi).build(); + when(bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)) + .thenReturn(Collections.singletonList(entity)); + when(mapper.toDto(entity)).thenReturn(dto); + + List result = service.getNotesForBook(bookId); + + assertEquals(1, result.size()); + assertEquals(noteId, result.getFirst().getId()); + assertEquals(cfi, result.getFirst().getCfi()); + verify(bookNoteV2Repository).findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId); + } + + @Test + void getNotesForBook_returnsEmptyList_whenNoNotes() { + when(bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)) + .thenReturn(Collections.emptyList()); + + List result = service.getNotesForBook(bookId); + + assertTrue(result.isEmpty()); + } + + @Test + void getNoteById_returnsNote_whenExists() { + BookNoteV2Entity entity = BookNoteV2Entity.builder().id(noteId).cfi(cfi).build(); + BookNoteV2 dto = BookNoteV2.builder().id(noteId).cfi(cfi).build(); + when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(entity)); + when(mapper.toDto(entity)).thenReturn(dto); + + BookNoteV2 result = service.getNoteById(noteId); + + assertEquals(noteId, result.getId()); + assertEquals(cfi, result.getCfi()); + } + + @Test + void getNoteById_throwsEntityNotFoundException_whenNotFound() { + when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty()); + + EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.getNoteById(noteId)); + + assertTrue(ex.getMessage().contains(String.valueOf(noteId))); + } + + @Test + void createNote_createsNewNote_withDefaultColor() { + CreateBookNoteV2Request request = CreateBookNoteV2Request.builder() + .bookId(bookId) + .cfi(cfi) + .selectedText(selectedText) + .noteContent(noteContent) + .chapterTitle(chapterTitle) + .build(); + + BookEntity book = BookEntity.builder().id(bookId).build(); + BookLoreUserEntity userEntity = BookLoreUserEntity.builder().id(userId).isDefaultPassword(false).build(); + BookNoteV2Entity savedEntity = BookNoteV2Entity.builder() + .id(noteId) + .cfi(cfi) + .selectedText(selectedText) + .noteContent(noteContent) + .color(defaultColor) + .chapterTitle(chapterTitle) + .build(); + BookNoteV2 dto = BookNoteV2.builder() + .id(noteId) + .cfi(cfi) + .selectedText(selectedText) + .noteContent(noteContent) + .color(defaultColor) + .chapterTitle(chapterTitle) + .build(); + + when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(userRepository.findById(userId)).thenReturn(Optional.of(userEntity)); + when(bookNoteV2Repository.save(any(BookNoteV2Entity.class))).thenReturn(savedEntity); + when(mapper.toDto(savedEntity)).thenReturn(dto); + + BookNoteV2 result = service.createNote(request); + + assertEquals(noteId, result.getId()); + assertEquals(defaultColor, result.getColor()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(BookNoteV2Entity.class); + verify(bookNoteV2Repository).save(captor.capture()); + BookNoteV2Entity captured = captor.getValue(); + assertEquals(cfi, captured.getCfi()); + assertEquals(selectedText, captured.getSelectedText()); + assertEquals(noteContent, captured.getNoteContent()); + assertEquals(defaultColor, captured.getColor()); + assertEquals(chapterTitle, captured.getChapterTitle()); + assertEquals(book, captured.getBook()); + assertEquals(userEntity, captured.getUser()); + } + + @Test + void createNote_createsNewNote_withCustomColor() { + CreateBookNoteV2Request request = CreateBookNoteV2Request.builder() + .bookId(bookId) + .cfi(cfi) + .selectedText(selectedText) + .noteContent(noteContent) + .color(customColor) + .chapterTitle(chapterTitle) + .build(); + + BookEntity book = BookEntity.builder().id(bookId).build(); + BookLoreUserEntity userEntity = BookLoreUserEntity.builder().id(userId).isDefaultPassword(false).build(); + BookNoteV2Entity savedEntity = BookNoteV2Entity.builder() + .id(noteId) + .color(customColor) + .build(); + BookNoteV2 dto = BookNoteV2.builder() + .id(noteId) + .color(customColor) + .build(); + + when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(userRepository.findById(userId)).thenReturn(Optional.of(userEntity)); + when(bookNoteV2Repository.save(any(BookNoteV2Entity.class))).thenReturn(savedEntity); + when(mapper.toDto(savedEntity)).thenReturn(dto); + + BookNoteV2 result = service.createNote(request); + + assertEquals(customColor, result.getColor()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(BookNoteV2Entity.class); + verify(bookNoteV2Repository).save(captor.capture()); + assertEquals(customColor, captor.getValue().getColor()); + } + + @Test + void createNote_throwsAPIException_whenDuplicateCfiExists() { + CreateBookNoteV2Request request = CreateBookNoteV2Request.builder() + .bookId(bookId) + .cfi(cfi) + .noteContent(noteContent) + .build(); + + when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(true); + + APIException ex = assertThrows(APIException.class, () -> service.createNote(request)); + + assertTrue(ex.getMessage().contains("Note already exists")); + verify(bookNoteV2Repository, never()).save(any()); + } + + @Test + void createNote_throwsEntityNotFoundException_whenBookNotFound() { + CreateBookNoteV2Request request = CreateBookNoteV2Request.builder() + .bookId(bookId) + .cfi(cfi) + .noteContent(noteContent) + .build(); + + when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false); + when(bookRepository.findById(bookId)).thenReturn(Optional.empty()); + + EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.createNote(request)); + + assertTrue(ex.getMessage().contains(String.valueOf(bookId))); + verify(bookNoteV2Repository, never()).save(any()); + } + + @Test + void createNote_throwsEntityNotFoundException_whenUserNotFound() { + CreateBookNoteV2Request request = CreateBookNoteV2Request.builder() + .bookId(bookId) + .cfi(cfi) + .noteContent(noteContent) + .build(); + + BookEntity book = BookEntity.builder().id(bookId).build(); + + when(bookNoteV2Repository.existsByCfiAndBookIdAndUserId(cfi, bookId, userId)).thenReturn(false); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(userRepository.findById(userId)).thenReturn(Optional.empty()); + + EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.createNote(request)); + + assertTrue(ex.getMessage().contains(String.valueOf(userId))); + verify(bookNoteV2Repository, never()).save(any()); + } + + @Test + void updateNote_updatesAllFields() { + UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder() + .noteContent("Updated content") + .color("#00FF00") + .chapterTitle("Updated chapter") + .build(); + + BookNoteV2Entity existingEntity = BookNoteV2Entity.builder() + .id(noteId) + .cfi(cfi) + .noteContent(noteContent) + .color(defaultColor) + .chapterTitle(chapterTitle) + .build(); + + BookNoteV2Entity savedEntity = BookNoteV2Entity.builder() + .id(noteId) + .cfi(cfi) + .noteContent("Updated content") + .color("#00FF00") + .chapterTitle("Updated chapter") + .build(); + + BookNoteV2 dto = BookNoteV2.builder() + .id(noteId) + .noteContent("Updated content") + .color("#00FF00") + .chapterTitle("Updated chapter") + .build(); + + when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(existingEntity)); + when(bookNoteV2Repository.save(existingEntity)).thenReturn(savedEntity); + when(mapper.toDto(savedEntity)).thenReturn(dto); + + BookNoteV2 result = service.updateNote(noteId, request); + + assertEquals("Updated content", result.getNoteContent()); + assertEquals("#00FF00", result.getColor()); + assertEquals("Updated chapter", result.getChapterTitle()); + + assertEquals("Updated content", existingEntity.getNoteContent()); + assertEquals("#00FF00", existingEntity.getColor()); + assertEquals("Updated chapter", existingEntity.getChapterTitle()); + } + + @Test + void updateNote_updatesOnlyNonNullFields() { + UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder() + .noteContent("Updated content") + .build(); + + BookNoteV2Entity existingEntity = BookNoteV2Entity.builder() + .id(noteId) + .cfi(cfi) + .noteContent(noteContent) + .color(defaultColor) + .chapterTitle(chapterTitle) + .build(); + + when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(existingEntity)); + when(bookNoteV2Repository.save(existingEntity)).thenReturn(existingEntity); + when(mapper.toDto(existingEntity)).thenReturn(BookNoteV2.builder().id(noteId).build()); + + service.updateNote(noteId, request); + + assertEquals("Updated content", existingEntity.getNoteContent()); + assertEquals(defaultColor, existingEntity.getColor()); + assertEquals(chapterTitle, existingEntity.getChapterTitle()); + } + + @Test + void updateNote_throwsEntityNotFoundException_whenNoteNotFound() { + UpdateBookNoteV2Request request = UpdateBookNoteV2Request.builder() + .noteContent("Updated content") + .build(); + + when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty()); + + EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.updateNote(noteId, request)); + + assertTrue(ex.getMessage().contains(String.valueOf(noteId))); + verify(bookNoteV2Repository, never()).save(any()); + } + + @Test + void deleteNote_deletesExistingNote() { + BookNoteV2Entity entity = BookNoteV2Entity.builder().id(noteId).build(); + when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.of(entity)); + + service.deleteNote(noteId); + + verify(bookNoteV2Repository).delete(entity); + } + + @Test + void deleteNote_throwsEntityNotFoundException_whenNotFound() { + when(bookNoteV2Repository.findByIdAndUserId(noteId, userId)).thenReturn(Optional.empty()); + + EntityNotFoundException ex = assertThrows(EntityNotFoundException.class, () -> service.deleteNote(noteId)); + + assertTrue(ex.getMessage().contains(String.valueOf(noteId))); + verify(bookNoteV2Repository, never()).delete(any()); + } + + @Test + void getNotesForBook_returnsMultipleNotes_orderedByCreatedAtDesc() { + BookNoteV2Entity entity1 = BookNoteV2Entity.builder().id(1L).cfi("cfi1").build(); + BookNoteV2Entity entity2 = BookNoteV2Entity.builder().id(2L).cfi("cfi2").build(); + BookNoteV2Entity entity3 = BookNoteV2Entity.builder().id(3L).cfi("cfi3").build(); + + BookNoteV2 dto1 = BookNoteV2.builder().id(1L).cfi("cfi1").build(); + BookNoteV2 dto2 = BookNoteV2.builder().id(2L).cfi("cfi2").build(); + BookNoteV2 dto3 = BookNoteV2.builder().id(3L).cfi("cfi3").build(); + + when(bookNoteV2Repository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)) + .thenReturn(List.of(entity3, entity2, entity1)); + when(mapper.toDto(entity3)).thenReturn(dto3); + when(mapper.toDto(entity2)).thenReturn(dto2); + when(mapper.toDto(entity1)).thenReturn(dto1); + + List result = service.getNotesForBook(bookId); + + assertEquals(3, result.size()); + assertEquals(3L, result.get(0).getId()); + assertEquals(2L, result.get(1).getId()); + assertEquals(1L, result.get(2).getId()); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-view-manager.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/core/event.service.ts similarity index 54% rename from booklore-ui/src/app/features/readers/ebook-reader/services/reader-view-manager.service.ts rename to booklore-ui/src/app/features/readers/ebook-reader/core/event.service.ts index 9a2b697cf..264d7610a 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-view-manager.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/core/event.service.ts @@ -1,41 +1,40 @@ -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'; +import {inject, Injectable} from '@angular/core'; +import {Subject} from 'rxjs'; +import {ReaderAnnotationService} from '../features/annotations/annotation-renderer.service'; export interface ViewEvent { - type: 'load' | 'relocate' | 'error' | 'middle-single-tap'; + type: 'load' | 'relocate' | 'error' | 'middle-single-tap' | 'draw-annotation' | 'show-annotation' | 'text-selected'; detail?: any; + popupPosition?: { x: number; y: number; showBelow?: boolean }; } -interface TocItem { - label: string; - href: string; - subitems?: TocItem[]; +export interface TextSelection { + text: string; + cfi: string; + range: Range; + index: number; } -export interface BookMetadata { - title?: string; - authors?: string[]; - language?: string; - publisher?: string; - description?: string; - identifier?: string; - coverUrl?: string; - - [key: string]: any; +interface ViewCallbacks { + prev: () => void; + next: () => void; + getCFI: (index: number, range: Range) => string | null; + getContents: () => Array<{ index: number; doc: Document }> | null; } @Injectable({ providedIn: 'root' }) -export class ReaderViewManagerService { +export class ReaderEventService { 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 annotationService = inject(ReaderAnnotationService); + private view: any; + private viewCallbacks: ViewCallbacks | null = null; private isNavigating = false; private lastClickTime = 0; private lastClickZone: 'left' | 'middle' | 'right' | null = null; @@ -46,39 +45,12 @@ export class ReaderViewManagerService { private eventSubject = new Subject(); 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(); + initialize(view: any, callbacks: ViewCallbacks): void { + this.view = view; + this.viewCallbacks = callbacks; + this.attachViewEventListeners(); this.attachKeyboardHandler(); - } - - loadEpub(epubPath: string): Observable { - 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); - }), - map(() => undefined), - catchError(err => throwError(() => err)) - ); + this.attachWindowMessageHandler(); } destroy(): void { @@ -86,108 +58,18 @@ export class ReaderViewManagerService { document.removeEventListener('keydown', this.keydownHandler); this.keydownHandler = undefined; } - this.view?.remove(); this.view = null; + this.viewCallbacks = null; + this.clickedDocs = new WeakSet(); } - goTo(target?: string | number | null): Observable { - const resolvedTarget = target ?? 0; - if (!this.view) { - return of(undefined); - } - return defer(() => - from(this.view.goTo(resolvedTarget) as Promise) - ).pipe( - map(() => undefined) - ); + emit(event: ViewEvent): void { + this.eventSubject.next(event); } - goToSection(index: number): Observable { - return this.goTo(index); - } + private attachViewEventListeners(): void { + if (!this.view) return; - goToFraction(fraction: number): Observable { - if (!this.view) { - return of(undefined); - } - return defer(() => from(this.view.goToFraction(fraction) as Promise)).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 { - 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 { - if (!this.view?.book?.getCover) { - return of(null); - } - return defer(() => { - const coverPromise = this.view.book.getCover(); - return coverPromise ? from(coverPromise as Promise) : of(null); - }); - } - - getCoverUrl(): Observable { - 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) { @@ -206,10 +88,18 @@ export class ReaderViewManagerService { this.eventSubject.next({type: 'error', detail: e.detail}); }); - window.addEventListener('message', (event) => { - if (event.data?.type === 'iframe-click') { - this.handleIframeClickMessage(event.data); + this.view.addEventListener('draw-annotation', (e: any) => { + const {draw, annotation, doc, range} = e.detail; + const storedStyle = this.annotationService.getAnnotationStyle(annotation.value); + if (storedStyle) { + const overlayerStyle = this.annotationService.getOverlayerDrawFunction(storedStyle.style); + draw(overlayerStyle, {color: storedStyle.color}); } + this.eventSubject.next({type: 'draw-annotation', detail: {annotation, doc, range}}); + }); + + this.view.addEventListener('show-annotation', (e: any) => { + this.eventSubject.next({type: 'show-annotation', detail: e.detail}); }); } @@ -217,28 +107,88 @@ export class ReaderViewManagerService { this.keydownHandler = (event: KeyboardEvent) => { const k = event.key; if (k === 'ArrowLeft' || k === 'h' || k === 'PageUp') { - this.prev(); + this.viewCallbacks?.prev(); event.preventDefault(); } else if (k === 'ArrowRight' || k === 'l' || k === 'PageDown') { - this.next(); + this.viewCallbacks?.next(); event.preventDefault(); } }; document.addEventListener('keydown', this.keydownHandler); } + private attachWindowMessageHandler(): void { + window.addEventListener('message', (event) => { + if (event.data?.type === 'iframe-click') { + this.handleIframeClickMessage(event.data); + } + }); + } + private attachIframeEventHandlers(doc: Document): void { if (this.clickedDocs.has(doc)) { return; } this.clickedDocs.add(doc); - doc.addEventListener('mousedown', (event: MouseEvent) => { + doc.addEventListener('mousedown', () => { this.longHoldTimeout = setTimeout(() => { this.longHoldTimeout = null; }, this.LONG_HOLD_THRESHOLD_MS); }, true); + doc.addEventListener('mouseup', (event: MouseEvent) => { + setTimeout(() => { + const selection = doc.defaultView?.getSelection(); + if (!selection || selection.isCollapsed || selection.rangeCount === 0) { + return; + } + + const range = selection.getRangeAt(0); + const text = range.toString().trim(); + if (!text) return; + + const contents = this.viewCallbacks?.getContents(); + if (!contents || contents.length === 0) return; + + const {index} = contents[0]; + const cfi = this.viewCallbacks?.getCFI(index, range); + + if (cfi) { + const iframe = doc.defaultView?.frameElement as HTMLIFrameElement | null; + const rangeRect = range.getBoundingClientRect(); + let popupX = rangeRect.left + (rangeRect.width / 2); + let selectionTop = rangeRect.top; + let selectionBottom = rangeRect.bottom; + + if (iframe) { + const iframeRect = iframe.getBoundingClientRect(); + popupX = iframeRect.left + rangeRect.left + (rangeRect.width / 2); + selectionTop = iframeRect.top + rangeRect.top; + selectionBottom = iframeRect.top + rangeRect.bottom; + } + + const minSpaceAbove = 120; + const showBelow = selectionTop < minSpaceAbove; + + let popupY: number; + if (showBelow) { + popupY = selectionBottom + 10; + } else { + popupY = selectionTop - 50; + } + + popupX = Math.max(100, Math.min(popupX, window.innerWidth - 150)); + + this.eventSubject.next({ + type: 'text-selected', + detail: {text, cfi, range, index}, + popupPosition: {x: popupX, y: popupY, showBelow} + }); + } + }, 10); + }); + doc.addEventListener('click', (event: MouseEvent) => { const iframe = doc.defaultView?.frameElement as HTMLIFrameElement | null; if (!iframe) return; @@ -260,6 +210,8 @@ export class ReaderViewManagerService { } private handleIframeClickMessage(data: any): void { + if (!this.view) return; + const now = Date.now(); const timeSinceLastClick = now - this.lastClickTime; @@ -307,6 +259,8 @@ export class ReaderViewManagerService { return; } + if (!this.view) return; + const viewRect = this.view.getBoundingClientRect(); const x = data.clientX - viewRect.left; const width = viewRect.width; @@ -316,11 +270,11 @@ export class ReaderViewManagerService { if (x < leftThreshold) { this.isNavigating = true; - this.prev(); + this.viewCallbacks?.prev(); setTimeout(() => this.isNavigating = false, 300); } else if (x > rightThreshold) { this.isNavigating = true; - this.next(); + this.viewCallbacks?.next(); setTimeout(() => this.isNavigating = false, 300); } else { this.eventSubject.next({type: 'middle-single-tap'}); diff --git a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-loader.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/core/loader.service.ts similarity index 100% rename from booklore-ui/src/app/features/readers/ebook-reader/services/reader-loader.service.ts rename to booklore-ui/src/app/features/readers/ebook-reader/core/loader.service.ts diff --git a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-style.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/core/style.service.ts similarity index 95% rename from booklore-ui/src/app/features/readers/ebook-reader/services/reader-style.service.ts rename to booklore-ui/src/app/features/readers/ebook-reader/core/style.service.ts index 246331f29..3d4fe4e4c 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-style.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/core/style.service.ts @@ -1,6 +1,6 @@ import {inject, Injectable} from '@angular/core'; -import {ReaderState} from './reader-state.service'; -import {EpubCustomFontService} from './epub-custom-font.service'; +import {ReaderState} from '../state/reader-state.service'; +import {EpubCustomFontService} from '../features/fonts/custom-font.service'; @Injectable({ providedIn: 'root' @@ -156,6 +156,12 @@ export class ReaderStyleService { } ${overrideFont ? '' : ''} ${userStylesheet} + ::selection { + background-color: rgba(128, 128, 128, 0.3); + } + ::-moz-selection { + background-color: rgba(128, 128, 128, 0.3); + } `; } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts new file mode 100644 index 000000000..a5b120b49 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts @@ -0,0 +1,231 @@ +import {inject, Injectable} from '@angular/core'; +import {defer, from, Observable, of, throwError, timer} from 'rxjs'; +import {catchError, map, switchMap} from 'rxjs/operators'; +import {ReaderAnnotationService, Annotation} from '../features/annotations/annotation-renderer.service'; +import {ReaderEventService, ViewEvent, TextSelection} from './event.service'; +import {PageInfo, ThemeInfo, PageDecorator} from '../shared/header-footer.util'; + +export type {ViewEvent, TextSelection} from './event.service'; +export type {PageInfo, ThemeInfo} from '../shared/header-footer.util'; + +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 annotationService = inject(ReaderAnnotationService); + private eventService = inject(ReaderEventService); + private view: any; + + public get events$(): Observable { + return this.eventService.events$; + } + + 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.eventService.initialize(this.view, { + prev: () => this.prev(), + next: () => this.next(), + getCFI: (index: number, range: Range) => this.view?.getCFI(index, range), + getContents: () => this.view?.renderer?.getContents() ?? null + }); + } + + loadEpub(epubPath: string): Observable { + 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); + }), + map(() => undefined), + catchError(err => throwError(() => err)) + ); + } + + destroy(): void { + this.eventService.destroy(); + this.annotationService.clearAnnotations(); + this.view?.remove(); + this.view = null; + } + + goTo(target?: string | number | null): Observable { + const resolvedTarget = target ?? 0; + if (!this.view) { + return of(undefined); + } + return defer(() => + from(this.view.goTo(resolvedTarget) as Promise) + ).pipe( + map(() => undefined) + ); + } + + goToSection(index: number): Observable { + return this.goTo(index); + } + + goToFraction(fraction: number): Observable { + if (!this.view) { + return of(undefined); + } + return defer(() => from(this.view.goToFraction(fraction) as Promise)).pipe( + map(() => undefined) + ); + } + + prev(): void { + this.view?.prev(); + } + + next(): void { + this.view?.next(); + } + + getRenderer(): any { + return this.view?.renderer; + } + + getSelection(): TextSelection | null { + const renderer = this.getRenderer(); + if (!renderer) return null; + + const contents = renderer.getContents(); + if (!contents || contents.length === 0) return null; + + const {index, doc} = contents[0]; + if (!doc) return null; + + const selection = doc.defaultView?.getSelection(); + if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null; + + const range = selection.getRangeAt(0); + const text = range.toString().trim(); + if (!text) return null; + + const cfi = this.view?.getCFI(index, range); + if (!cfi) return null; + + return {text, cfi, range, index}; + } + + clearSelection(): void { + this.view?.deselect(); + } + + addAnnotation(annotation: Annotation): Observable<{index: number; label: string} | undefined> { + return this.annotationService.addAnnotation(this.view, annotation); + } + + deleteAnnotation(cfi: string): Observable { + return this.annotationService.deleteAnnotation(this.view, cfi); + } + + addAnnotations(annotations: Annotation[]): void { + this.annotationService.addAnnotations(this.view, annotations); + } + + updateHeadersAndFooters(chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void { + const renderer = this.getRenderer(); + PageDecorator.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 { + 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 { + if (!this.view?.book?.getCover) { + return of(null); + } + return defer(() => { + const coverPromise = this.view.book.getCover(); + return coverPromise ? from(coverPromise as Promise) : of(null); + }); + } + + getCoverUrl(): Observable { + return this.getCover().pipe( + map(blob => blob ? URL.createObjectURL(blob) : null) + ); + } + + async* search(opts: { query: string; matchCase?: boolean; matchWholeWords?: boolean }): AsyncGenerator { + if (!this.view?.search) return; + yield* this.view.search(opts); + } + + clearSearch(): void { + this.view?.clearSearch?.(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.html b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.html similarity index 100% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.html rename to booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.html diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.scss similarity index 58% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.scss rename to booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.scss index 6879b9dea..0f848b703 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.scss +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.scss @@ -1,27 +1,35 @@ +// Variables matching sidebar styling +$dialog-bg: #1a1a1a; +$text-primary: rgba(255, 255, 255, 0.95); +$text-secondary: rgba(255, 255, 255, 0.6); +$text-muted: rgba(255, 255, 255, 0.4); +$border-color: rgba(255, 255, 255, 0.08); +$hover-bg: rgba(255, 255, 255, 0.08); +$active-color: #818cf8; +$active-bg: rgba(129, 140, 248, 0.15); +$transition-fast: 150ms ease; +$transition-normal: 200ms ease; + .dialog-overlay { position: fixed; inset: 0; - background: rgba(0, 0, 0, 0.2); + background: rgba(0, 0, 0, 0.5); + backdrop-filter: blur(4px); z-index: 12000; display: flex; align-items: center; justify-content: center; - animation: fadeIn 0.2s ease-out; + animation: fadeIn $transition-normal; } @keyframes fadeIn { - from { - opacity: 0; - } - to { - opacity: 1; - } + from { opacity: 0; } + to { opacity: 1; } } .dialog { - background: rgba(30, 30, 30, 0.95); - backdrop-filter: blur(20px); - -webkit-backdrop-filter: blur(20px); + background: $dialog-bg; + border: 1px solid $border-color; border-radius: 12px; width: 90%; max-width: 800px; @@ -30,7 +38,7 @@ flex-direction: column; overflow: hidden; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); - animation: slideUp 0.3s ease-out; + animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1); @media (max-width: 768px) { width: 95%; @@ -52,7 +60,7 @@ .dialog-header { padding: 16px 20px; - border-bottom: 1px solid rgba(255, 255, 255, 0.08); + border-bottom: 1px solid $border-color; display: flex; align-items: center; justify-content: space-between; @@ -60,9 +68,9 @@ h2 { margin: 0; - font-size: 18px; + font-size: 16px; font-weight: 600; - color: #ffffff; + color: $text-primary; letter-spacing: -0.3px; } } @@ -70,17 +78,27 @@ .close-btn { background: none; border: none; - color: rgba(255, 255, 255, 0.6); - font-size: 20px; + color: $text-muted; + font-size: 18px; cursor: pointer; - padding: 4px 8px; + padding: 6px; border-radius: 6px; - transition: all 0.2s ease; + transition: background $transition-fast, color $transition-fast; line-height: 1; + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; &:hover { - background: rgba(255, 255, 255, 0.08); - color: rgba(255, 255, 255, 0.9); + background: $hover-bg; + color: $text-primary; + } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 2px; } } @@ -95,7 +113,7 @@ } &::-webkit-scrollbar { - width: 8px; + width: 6px; } &::-webkit-scrollbar-track { @@ -104,7 +122,7 @@ &::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.15); - border-radius: 4px; + border-radius: 3px; &:hover { background: rgba(255, 255, 255, 0.25); @@ -118,17 +136,17 @@ @media (max-width: 768px) { flex-direction: column; - gap: 16px; + gap: 20px; } } .cover-section { flex-shrink: 0; - width: 240px; + width: 200px; @media (max-width: 768px) { width: 100%; - max-width: 180px; + max-width: 160px; margin: 0 auto; } } @@ -138,34 +156,34 @@ height: auto; border-radius: 8px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4); - max-height: 360px; + max-height: 300px; object-fit: cover; @media (max-width: 768px) { - max-height: 270px; + max-height: 240px; } } .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); + background: linear-gradient(135deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.01) 100%); + border: 2px dashed rgba(255, 255, 255, 0.12); border-radius: 8px; display: flex; align-items: center; justify-content: center; @media (max-width: 768px) { - max-height: 270px; + max-height: 240px; } .placeholder-icon { - font-size: 64px; + font-size: 56px; opacity: 0.3; @media (max-width: 768px) { - font-size: 48px; + font-size: 44px; } } } @@ -174,20 +192,21 @@ flex: 1; display: flex; flex-direction: column; - gap: 20px; + gap: 16px; + min-width: 0; } .metadata-group { - animation: fadeIn 0.2s ease-out; + animation: fadeIn $transition-normal; &:not(:last-child) { padding-bottom: 16px; - border-bottom: 1px solid rgba(255, 255, 255, 0.06); + border-bottom: 1px solid $border-color; } } .section-title { - color: rgba(255, 255, 255, 0.5); + color: $text-muted; font-size: 11px; font-weight: 600; text-transform: uppercase; @@ -197,7 +216,7 @@ .metadata-item { display: grid; - grid-template-columns: 120px 1fr; + grid-template-columns: 110px 1fr; gap: 12px; margin-bottom: 10px; align-items: start; @@ -213,25 +232,29 @@ } .label { - color: rgba(255, 255, 255, 0.6); + color: $text-secondary; font-size: 13px; font-weight: 500; } .value { - color: rgba(255, 255, 255, 0.95); + color: $text-primary; font-size: 13px; word-break: break-word; + line-height: 1.5; &.file-name { - font-family: 'Courier New', monospace; + font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace; font-size: 12px; - color: rgba(255, 255, 255, 0.8); + color: $text-secondary; + background: rgba(255, 255, 255, 0.03); + padding: 4px 8px; + border-radius: 4px; } } .review-count { - color: rgba(255, 255, 255, 0.5); + color: $text-muted; font-size: 12px; margin-left: 4px; } @@ -243,19 +266,24 @@ } .tag { - background: rgba(74, 158, 255, 0.15); - color: rgba(255, 255, 255, 0.9); + background: $active-bg; + color: $text-primary; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; - border: 1px solid rgba(74, 158, 255, 0.25); + border: 1px solid rgba(129, 140, 248, 0.2); + transition: background $transition-fast; + + &:hover { + background: rgba(129, 140, 248, 0.25); + } } .description { - color: rgba(255, 255, 255, 0.8); + color: $text-secondary; font-size: 13px; - line-height: 1.6; + line-height: 1.7; margin: 0; white-space: pre-wrap; } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.ts similarity index 83% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.ts rename to booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.ts index 48facf81c..c390130b4 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-book-metadata-dialog.component.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/metadata-dialog.component.ts @@ -1,14 +1,14 @@ 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'; +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'] + templateUrl: './metadata-dialog.component.html', + styleUrls: ['./metadata-dialog.component.scss'] }) export class ReaderBookMetadataDialogComponent { @Input() book: Book | null = null; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.html b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.html new file mode 100644 index 000000000..00a76a5c7 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.html @@ -0,0 +1,51 @@ +
+
+
+

{{ isEditing ? 'Edit Note' : 'Add Note' }}

+ +
+ +
+ @if (data?.selectedText) { +
+ +

"{{ data?.selectedText }}"

+
+ } + +
+ + +
+ +
+ +
+ @for (color of noteColors; track color.value) { + + } +
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.scss new file mode 100644 index 000000000..d7db2795a --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.scss @@ -0,0 +1,261 @@ +// Variables matching reader styling +$dialog-bg: #1a1a1a; +$text-primary: rgba(255, 255, 255, 0.95); +$text-secondary: rgba(255, 255, 255, 0.6); +$text-muted: rgba(255, 255, 255, 0.4); +$border-color: rgba(255, 255, 255, 0.08); +$hover-bg: rgba(255, 255, 255, 0.08); +$active-color: #818cf8; +$active-bg: rgba(129, 140, 248, 0.15); +$transition-fast: 150ms ease; +$transition-normal: 200ms ease; + +.dialog-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.5); + backdrop-filter: blur(4px); + z-index: 13000; + display: flex; + align-items: center; + justify-content: center; + animation: fadeIn $transition-normal; +} + +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +.dialog { + background: $dialog-bg; + border: 1px solid $border-color; + border-radius: 12px; + width: 90%; + max-width: 500px; + max-height: 85vh; + display: flex; + flex-direction: column; + overflow: hidden; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); + animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1); +} + +@keyframes slideUp { + from { + transform: translateY(20px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +.dialog-header { + padding: 16px 20px; + border-bottom: 1px solid $border-color; + 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: 16px; + font-weight: 600; + color: $text-primary; + letter-spacing: -0.3px; + } +} + +.close-btn { + background: none; + border: none; + color: $text-muted; + cursor: pointer; + padding: 6px; + border-radius: 6px; + transition: background $transition-fast, color $transition-fast; + line-height: 1; + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + background: $hover-bg; + color: $text-primary; + } +} + +.dialog-body { + padding: 20px; + overflow-y: auto; + flex: 1; + display: flex; + flex-direction: column; + gap: 20px; + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background: transparent; + } + + &::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.15); + border-radius: 3px; + + &:hover { + background: rgba(255, 255, 255, 0.25); + } + } +} + +.section-label { + display: block; + color: $text-muted; + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 1px; + margin-bottom: 8px; +} + +.selected-text-section { + .selected-text { + margin: 0; + padding: 12px 16px; + background: rgba(255, 255, 255, 0.03); + border-left: 3px solid $active-color; + border-radius: 0 8px 8px 0; + color: $text-secondary; + font-size: 13px; + font-style: italic; + line-height: 1.6; + max-height: 100px; + overflow-y: auto; + } +} + +.note-section { + flex: 1; + display: flex; + flex-direction: column; +} + +.note-input { + flex: 1; + min-height: 120px; + padding: 12px 16px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid $border-color; + border-radius: 8px; + color: $text-primary; + font-size: 14px; + line-height: 1.6; + resize: vertical; + font-family: inherit; + transition: border-color $transition-fast, box-shadow $transition-fast; + + &::placeholder { + color: $text-muted; + } + + &:focus { + outline: none; + border-color: $active-color; + box-shadow: 0 0 0 3px rgba(129, 140, 248, 0.15); + } +} + +.color-section { + .color-buttons { + display: flex; + gap: 10px; + } +} + +.color-btn { + width: 32px; + height: 32px; + border-radius: 50%; + border: 2px solid transparent; + background: var(--color); + cursor: pointer; + transition: transform $transition-fast, border-color $transition-fast, box-shadow $transition-fast; + position: relative; + + &:hover { + transform: scale(1.1); + } + + &.selected { + border-color: $text-primary; + box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.2); + + &::after { + content: '✓'; + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + color: white; + font-size: 14px; + font-weight: bold; + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5); + } + } +} + +.dialog-footer { + padding: 16px 20px; + border-top: 1px solid $border-color; + display: flex; + justify-content: flex-end; + gap: 12px; + background: linear-gradient(0deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%); +} + +.btn { + padding: 10px 20px; + border-radius: 8px; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: background $transition-fast, transform $transition-fast, opacity $transition-fast; + border: none; + + &:active { + transform: scale(0.98); + } + + &:disabled { + opacity: 0.5; + cursor: not-allowed; + transform: none; + } +} + +.btn-secondary { + background: $hover-bg; + color: $text-primary; + + &:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.12); + } +} + +.btn-primary { + background: $active-color; + color: white; + + &:hover:not(:disabled) { + background: #9ba3fa; + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.ts new file mode 100644 index 000000000..4cc51be9a --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/note-dialog.component.ts @@ -0,0 +1,77 @@ +import {Component, EventEmitter, Input, Output, OnChanges, SimpleChanges} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {FormsModule} from '@angular/forms'; +import {ReaderIconComponent} from '../shared/icon.component'; + +export interface NoteDialogData { + cfi: string; + selectedText?: string; + chapterTitle?: string; + noteId?: number; + noteContent?: string; + color?: string; +} + +export interface NoteDialogResult { + noteContent: string; + color: string; +} + +@Component({ + selector: 'app-reader-note-dialog', + standalone: true, + imports: [CommonModule, FormsModule, ReaderIconComponent], + templateUrl: './note-dialog.component.html', + styleUrls: ['./note-dialog.component.scss'] +}) +export class ReaderNoteDialogComponent implements OnChanges { + @Input() data: NoteDialogData | null = null; + @Output() save = new EventEmitter(); + @Output() cancel = new EventEmitter(); + + noteContent = ''; + selectedColor = '#FFC107'; + + get isEditing(): boolean { + return !!this.data?.noteId; + } + + ngOnChanges(changes: SimpleChanges): void { + if (changes['data'] && this.data) { + this.noteContent = this.data.noteContent || ''; + this.selectedColor = this.data.color || '#FFC107'; + } + } + + noteColors = [ + {value: '#FFC107', label: 'Amber'}, + {value: '#4CAF50', label: 'Green'}, + {value: '#2196F3', label: 'Blue'}, + {value: '#E91E63', label: 'Pink'}, + {value: '#9C27B0', label: 'Purple'}, + {value: '#FF5722', label: 'Deep Orange'} + ]; + + onSave(): void { + if (this.noteContent.trim()) { + this.save.emit({ + noteContent: this.noteContent.trim(), + color: this.selectedColor + }); + } + } + + onCancel(): void { + this.cancel.emit(); + } + + selectColor(color: string): void { + this.selectedColor = color; + } + + onOverlayClick(event: MouseEvent): void { + if ((event.target as HTMLElement).classList.contains('dialog-overlay')) { + this.onCancel(); + } + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.html b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.html similarity index 91% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.html rename to booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.html index fe75ab4b0..691c6bd2f 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.html +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.html @@ -58,6 +58,22 @@ } + +
Annotation Highlighter
+
+ @for (color of annotationColors; track color.name) { + + } +
} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.scss similarity index 56% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.scss rename to booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.scss index de1ce1bda..67d49cef6 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.scss +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.scss @@ -1,27 +1,34 @@ +// Variables matching sidebar styling +$dialog-bg: #1a1a1a; +$text-primary: rgba(255, 255, 255, 0.95); +$text-secondary: rgba(255, 255, 255, 0.6); +$text-muted: rgba(255, 255, 255, 0.4); +$border-color: rgba(255, 255, 255, 0.08); +$hover-bg: rgba(255, 255, 255, 0.08); +$active-color: #818cf8; +$active-bg: rgba(129, 140, 248, 0.15); +$transition-fast: 150ms ease; +$transition-normal: 200ms ease; + .dialog-overlay { position: fixed; inset: 0; - background: rgba(0, 0, 0, 0.2); + background: rgba(0, 0, 0, 0.25); z-index: 12000; display: flex; align-items: center; justify-content: center; - animation: fadeIn 0.2s ease-out; + animation: fadeIn $transition-normal; } @keyframes fadeIn { - from { - opacity: 0; - } - to { - opacity: 1; - } + from { opacity: 0; } + to { opacity: 1; } } .dialog { - background: rgba(30, 30, 30, 0.95); - backdrop-filter: blur(20px); - -webkit-backdrop-filter: blur(20px); + background: $dialog-bg; + border: 1px solid $border-color; border-radius: 12px; width: 90%; max-width: 520px; @@ -29,7 +36,7 @@ max-height: 85vh; overflow: hidden; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); - animation: slideUp 0.3s ease-out; + animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1); display: flex; flex-direction: column; } @@ -45,30 +52,12 @@ } } -.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); + border-bottom: 1px solid $border-color; + background: rgba(0, 0, 0, 0.2); padding: 0 20px; - margin-bottom: 18px; justify-content: center; position: relative; } @@ -80,77 +69,77 @@ flex: 0 1 auto; } -.tabs-row-spacer { - display: none; -} - .tab { background: none; border: none; - color: rgba(255, 255, 255, 0.6); - padding: 12px 18px; + color: $text-secondary; + padding: 14px 20px; cursor: pointer; - font-size: 14px; + font-size: 13px; font-weight: 500; position: relative; - transition: all 0.2s ease; + transition: color $transition-fast; text-align: center; - min-width: 80px; + min-width: 90px; display: flex; align-items: center; justify-content: center; &:hover { - color: rgba(255, 255, 255, 0.8); + color: $text-primary; } &.active { - color: #ffffff; + color: $active-color; &::after { content: ''; position: absolute; - left: 50%; + left: 16px; + right: 16px; bottom: 0; - transform: translateX(-50%); - width: 60%; height: 2px; - background: #4a9eff; - border-radius: 1px; + background: $active-color; + border-radius: 1px 1px 0 0; } } } .close-btn { position: absolute; - right: 20px; + right: 16px; top: 50%; transform: translateY(-50%); - margin-left: 0; background: none; border: none; - color: rgba(255, 255, 255, 0.6); - font-size: 20px; + color: $text-muted; + font-size: 18px; cursor: pointer; + padding: 6px; border-radius: 6px; - transition: all 0.2s ease; + transition: background $transition-fast, color $transition-fast; line-height: 1; + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; &:hover { - background: rgba(255, 255, 255, 0.08); - color: rgba(255, 255, 255, 0.9); + background: $hover-bg; + color: $text-primary; } } .dialog-body { - padding: 20px 25px; + padding: 20px 24px; overflow-y: auto; flex: 1 1 0; min-height: 0; max-height: 100%; &::-webkit-scrollbar { - width: 8px; + width: 6px; } &::-webkit-scrollbar-track { @@ -159,51 +148,42 @@ &::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.15); - border-radius: 4px; + border-radius: 3px; &: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; + animation: fadeIn $transition-normal; } -.mode-toggle, -.toggle-control { - display: flex; - align-items: center; - justify-content: space-between; - padding: 12px 0; - margin-bottom: 2px; +.section-header { + color: $text-muted; + 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 $border-color; - span { - color: rgba(255, 255, 255, 0.9); - font-size: 14px; - font-weight: 500; + &: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: 24px; + border-bottom: 1px solid $border-color; } } @@ -216,7 +196,7 @@ .mode-icon { font-size: 18px; opacity: 0.3; - transition: all 0.3s ease; + transition: all 300ms ease; user-select: none; &.active { @@ -241,6 +221,20 @@ } } +.toggle-control { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 0; + margin-bottom: 2px; + + span { + color: $text-primary; + font-size: 14px; + font-weight: 500; + } +} + .switch { position: relative; width: 44px; @@ -249,11 +243,11 @@ border: none; border-radius: 12px; cursor: pointer; - transition: background 0.3s ease; + transition: background 300ms ease; padding: 0; &.active { - background: #4a9eff; + background: $active-color; .slider { transform: translateX(20px); @@ -268,7 +262,7 @@ height: 20px; background: #ffffff; border-radius: 50%; - transition: transform 0.3s ease; + transition: transform 300ms ease; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); } @@ -276,15 +270,20 @@ background: rgba(255, 255, 255, 0.2); &.active { - background: #5ba9ff; + background: #9aa3fa; } } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 2px; + } } .theme-grid { display: grid; grid-template-columns: repeat(4, 1fr); - gap: 14px; + gap: 12px; margin-bottom: 16px; } @@ -302,24 +301,24 @@ } .theme-card { - background: rgba(255, 255, 255, 0.05); - border: 2px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.03); + border: 2px solid $border-color; border-radius: 8px; padding: 10px; - transition: all 0.2s ease; + transition: all $transition-fast; display: flex; flex-direction: column; gap: 8px; &:hover { - background: rgba(255, 255, 255, 0.08); - border-color: rgba(255, 255, 255, 0.2); + background: $hover-bg; + border-color: rgba(255, 255, 255, 0.15); } } input:checked + .theme-card { - border-color: #4a9eff; - background: rgba(74, 158, 255, 0.1); + border-color: $active-color; + background: $active-bg; } .theme-colors { @@ -330,13 +329,13 @@ .color-swatch { flex: 1; - border-radius: 3px; + border-radius: 4px; border: 1px solid rgba(0, 0, 0, 0.2); } .theme-name { - color: rgba(255, 255, 255, 0.9); - font-size: 12px; + color: $text-primary; + font-size: 11px; font-weight: 500; text-align: center; } @@ -345,41 +344,41 @@ .font-grid { display: grid; grid-template-columns: repeat(3, 1fr); - gap: 14px; + gap: 12px; margin-bottom: 20px; } .font-option { - background: rgba(255, 255, 255, 0.05); - border: 2px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.03); + border: 2px solid $border-color; border-radius: 8px; - padding: 10px; + padding: 12px; cursor: pointer; - transition: all 0.2s ease; + transition: all $transition-fast; 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); + background: $hover-bg; + border-color: rgba(255, 255, 255, 0.15); } &.active { - border-color: #4a9eff; - background: rgba(74, 158, 255, 0.1); + border-color: $active-color; + background: $active-bg; } .font-preview { font-size: 24px; - color: #ffffff; + color: $text-primary; line-height: 1; } .font-name { - color: rgba(255, 255, 255, 0.7); - font-size: 12px; + color: $text-secondary; + font-size: 11px; font-weight: 500; text-align: center; } @@ -397,39 +396,12 @@ } > label { - color: rgba(255, 255, 255, 0.9); + color: $text-primary; 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; @@ -438,20 +410,21 @@ border-radius: 3px; outline: none; cursor: pointer; + -webkit-appearance: none; &::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; border-radius: 50%; - background: #4a9eff; + background: $active-color; cursor: pointer; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3); - transition: all 0.2s ease; + transition: all $transition-fast; &:hover { transform: scale(1.1); - box-shadow: 0 2px 8px rgba(74, 158, 255, 0.5); + box-shadow: 0 2px 8px rgba(129, 140, 248, 0.5); } } @@ -459,54 +432,20 @@ width: 14px; height: 14px; border-radius: 50%; - background: #4a9eff; + background: $active-color; 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); + color: $text-secondary; 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 { @@ -534,16 +473,16 @@ display: flex; align-items: center; gap: 4px; - background: rgba(255, 255, 255, 0.05); + background: rgba(255, 255, 255, 0.03); padding: 3px; border-radius: 6px; - border: 1px solid rgba(255, 255, 255, 0.1); + border: 1px solid $border-color; button { width: 28px; height: 28px; - background: rgba(255, 255, 255, 0.08); - color: rgba(255, 255, 255, 0.9); + background: rgba(255, 255, 255, 0.05); + color: $text-secondary; border: none; border-radius: 4px; cursor: pointer; @@ -551,12 +490,12 @@ display: flex; align-items: center; justify-content: center; - transition: all 0.2s ease; + transition: all $transition-fast; font-weight: 300; &:hover { - background: rgba(255, 255, 255, 0.15); - color: #ffffff; + background: $hover-bg; + color: $text-primary; } &:active { @@ -567,71 +506,13 @@ span { min-width: 48px; text-align: center; - color: #ffffff; + color: $text-primary; 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; @@ -642,7 +523,7 @@ gap: 7px; cursor: pointer; font-size: 14px; - color: rgba(255, 255, 255, 0.85); + color: $text-primary; font-weight: 500; position: relative; user-select: none; @@ -651,22 +532,72 @@ appearance: none; width: 18px; height: 18px; - border: 2px solid #4a9eff; + border: 2px solid $active-color; border-radius: 50%; - background: rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.05); margin: 0 6px 0 0; outline: none; - transition: border-color 0.2s, box-shadow 0.2s; + transition: border-color $transition-fast, box-shadow $transition-fast; &:checked { - background: #4a9eff; - box-shadow: 0 0 0 2px rgba(74, 158, 255, 0.15); - border-color: #4a9eff; + background: $active-color; + box-shadow: 0 0 0 2px rgba(129, 140, 248, 0.15); + border-color: $active-color; } - &:focus { - box-shadow: 0 0 0 2px #4a9eff; + &:focus-visible { + box-shadow: 0 0 0 2px $active-color; } } } } + +.annotation-colors { + display: flex; + gap: 14px; + margin-bottom: 20px; + justify-content: center; + padding: 8px 0; +} + +.color-picker-btn { + width: 44px; + height: 44px; + border-radius: 50%; + border: 3px solid rgba(255, 255, 255, 0.15); + cursor: pointer; + transition: all $transition-fast; + position: relative; + display: flex; + align-items: center; + justify-content: center; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + + &:hover { + transform: scale(1.08); + border-color: rgba(255, 255, 255, 0.3); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + } + + &:active { + transform: scale(0.98); + } + + &.active { + border-color: $active-color; + border-width: 3px; + box-shadow: 0 0 0 3px rgba(129, 140, 248, 0.25), 0 4px 12px rgba(0, 0, 0, 0.3); + + .check-icon { + color: rgba(0, 0, 0, 0.7); + font-size: 18px; + font-weight: bold; + text-shadow: 0 1px 2px rgba(255, 255, 255, 0.5); + } + } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 2px; + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.ts similarity index 75% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.ts rename to booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.ts index 7dfbca356..46bcf5b1f 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-settings-dialog.component.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/dialogs/settings-dialog.component.ts @@ -1,17 +1,23 @@ 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 {EbookViewerSetting} from '../../../../book/model/book.model'; -import {EpubCustomFontService} from '../../services/epub-custom-font.service'; +import {ReaderStateService} from '../state/reader-state.service'; +import {ReaderViewManagerService} from '../core/view-manager.service'; +import {BookService} from '../../../book/service/book.service'; +import {EbookViewerSetting} from '../../../book/model/book.model'; +import {EpubCustomFontService} from '../features/fonts/custom-font.service'; + +interface AnnotationColor { + name: string; + value: string; + label: string; +} @Component({ selector: 'app-settings-dialog', standalone: true, imports: [DecimalPipe], - templateUrl: './reader-settings-dialog.component.html', - styleUrls: ['./reader-settings-dialog.component.scss'] + templateUrl: './settings-dialog.component.html', + styleUrls: ['./settings-dialog.component.scss'] }) export class ReaderSettingsDialogComponent implements OnInit { @Input() stateService!: ReaderStateService; @@ -22,6 +28,16 @@ export class ReaderSettingsDialogComponent implements OnInit { activeTab: 'theme' | 'typography' | 'layout' = 'theme'; + selectedAnnotationColor: string = '#FFFF00'; + + annotationColors: AnnotationColor[] = [ + {name: 'yellow', value: '#FFFF00', label: 'Yellow'}, + {name: 'green', value: '#90EE90', label: 'Green'}, + {name: 'blue', value: '#87CEEB', label: 'Blue'}, + {name: 'pink', value: '#FFB6C1', label: 'Pink'}, + {name: 'orange', value: '#FFD580', label: 'Orange'} + ]; + constructor( private bookService: BookService, private customFontService: EpubCustomFontService, @@ -32,6 +48,7 @@ export class ReaderSettingsDialogComponent implements OnInit { ngOnInit() { this.customFontService.injectCustomFontsStylesheet(this.renderer, this.document); + this.selectedAnnotationColor = this.getSelectedAnnotationColor(); } getFontFamilyForPreview(fontValue: string): string { @@ -154,4 +171,14 @@ export class ReaderSettingsDialogComponent implements OnInit { this.viewManager.getRenderer()?.setAttribute?.('flow', flow); this.syncSettingsToBackend(); } + + setAnnotationColor(color: string): void { + this.selectedAnnotationColor = color; + localStorage.setItem('selectedAnnotationColor', color); + } + + getSelectedAnnotationColor(): string { + const stored = localStorage.getItem('selectedAnnotationColor'); + return stored || this.selectedAnnotationColor; + } } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html index ad7894505..9a8be19c9 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html +++ b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html @@ -11,41 +11,11 @@ } - - +
@if (isCurrentCfiBookmarked) { -
+
@@ -61,21 +31,16 @@ (progressChange)="onProgressChange($event)"> - @if (showChapters) { - + + + + @if (showQuickSettings) { + + } @if (showControls) { @@ -93,4 +58,21 @@ (close)="showMetadata = false" > } + + + + @if (showNoteDialog) { + + }
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss index 2f28b0f14..4f76c7af5 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss +++ b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss @@ -19,6 +19,17 @@ height: 100%; } +.bookmark-indicator { + position: absolute; + top: 0; + left: 12px; + z-index: 10; + width: 48px; + height: 64px; + background: none; + pointer-events: none; +} + .navigation-overlay { position: absolute; top: 0; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts index e4783cbc1..0f8691ad1 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts @@ -1,27 +1,34 @@ import {Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, inject, OnDestroy, OnInit} from '@angular/core'; -import {CommonModule, Location} from '@angular/common'; +import {CommonModule} 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 {MessageService} from 'primeng/api'; +import {ReaderLoaderService} from './core/loader.service'; +import {ReaderViewManagerService} from './core/view-manager.service'; +import {ReaderStateService} from './state/reader-state.service'; +import {ReaderStyleService} from './core/style.service'; +import {ReaderBookmarkService} from './features/bookmarks/bookmark.service'; +import {ReaderAnnotationHttpService} from './features/annotations/annotation.service'; +import {ReaderProgressService} from './state/progress.service'; +import {ReaderSelectionService} from './features/selection/selection.service'; +import {ReaderSidebarService} from './layout/sidebar/sidebar.service'; +import {ReaderLeftSidebarService} from './layout/panel/panel.service'; +import {ReaderHeaderService} from './layout/header/header.service'; +import {ReaderNoteService} from './features/notes/note.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 {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'; -import {EpubCustomFontService} from './services/epub-custom-font.service'; +import {Book} from '../../book/model/book.model'; +import {ReaderHeaderComponent} from './layout/header/header.component'; +import {ReaderSidebarComponent} from './layout/sidebar/sidebar.component'; +import {ReaderLeftSidebarComponent} from './layout/panel/panel.component'; +import {ReaderNavbarComponent} from './layout/footer/footer.component'; +import {ReaderSettingsDialogComponent} from './dialogs/settings-dialog.component'; +import {ReaderQuickSettingsComponent} from './layout/header/quick-settings.component'; +import {ReaderBookMetadataDialogComponent} from './dialogs/metadata-dialog.component'; +import {ReaderHeaderFooterVisibilityManager} from './shared/visibility.util'; +import {EpubCustomFontService} from './features/fonts/custom-font.service'; +import {TextSelectionPopupComponent, TextSelectionAction} from './shared/selection-popup.component'; +import {ReaderNoteDialogComponent, NoteDialogData, NoteDialogResult} from './dialogs/note-dialog.component'; @Component({ selector: 'app-ebook-reader', @@ -30,17 +37,29 @@ import {EpubCustomFontService} from './services/epub-custom-font.service'; CommonModule, ReaderHeaderComponent, ReaderSettingsDialogComponent, + ReaderQuickSettingsComponent, ReaderBookMetadataDialogComponent, ReaderSidebarComponent, - ReaderNavbarComponent + ReaderLeftSidebarComponent, + ReaderNavbarComponent, + TextSelectionPopupComponent, + ReaderNoteDialogComponent ], schemas: [CUSTOM_ELEMENTS_SCHEMA], providers: [ + MessageService, ReaderLoaderService, ReaderViewManagerService, ReaderStateService, ReaderStyleService, - ReaderBookmarkService + ReaderBookmarkService, + ReaderAnnotationHttpService, + ReaderProgressService, + ReaderSelectionService, + ReaderSidebarService, + ReaderLeftSidebarService, + ReaderHeaderService, + ReaderNoteService ], templateUrl: './ebook-reader.component.html', styleUrls: ['./ebook-reader.component.scss'] @@ -51,65 +70,96 @@ export class EbookReaderComponent implements OnInit, OnDestroy { 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); + private annotationService = inject(ReaderAnnotationHttpService); + private progressService = inject(ReaderProgressService); + private selectionService = inject(ReaderSelectionService); + private headerService = inject(ReaderHeaderService); + private noteService = inject(ReaderNoteService); + public sidebarService = inject(ReaderSidebarService); + public leftSidebarService = inject(ReaderLeftSidebarService); 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; + isLoading = true; + showQuickSettings = false; + showControls = false; + showMetadata = false; + isCurrentCfiBookmarked = false; + forceNavbarVisible = false; + book: Book | null = null; sectionFractions: number[] = []; + showSelectionPopup = false; + popupPosition = { x: 0, y: 0 }; + showPopupBelow = false; + overlappingAnnotationId: number | null = null; + selectedText = ''; + + showNoteDialog = false; + noteDialogData: NoteDialogData | null = null; + + get currentProgressData(): any { + return this.progressService.currentProgressData; + } + ngOnInit() { this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight); this.visibilityManager.onStateChange((state) => { - this.forceHeaderVisible = state.headerVisible; + this.headerService.setForceVisible(state.headerVisible); this.forceNavbarVisible = state.footerVisible; }); + this.selectionService.state$ + .pipe(takeUntil(this.destroy$)) + .subscribe(state => { + this.showSelectionPopup = state.visible; + this.popupPosition = state.position; + this.showPopupBelow = state.showBelow; + this.overlappingAnnotationId = state.overlappingAnnotationId; + this.selectedText = state.selectedText; + }); + + this.sidebarService.showMetadata$ + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.showMetadata = true); + + this.noteService.dialogState$ + .pipe(takeUntil(this.destroy$)) + .subscribe(state => { + this.showNoteDialog = state.visible; + this.noteDialogData = state.data; + }); + + this.headerService.showControls$ + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.showQuickSettings = true); + + this.headerService.showMetadata$ + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.showMetadata = true); + 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; + this.subscribeToStateChanges(); }), - catchError(err => { + switchMap(() => this.loadBookFromAPI()), + tap(() => this.isLoading = false), + catchError(() => { this.isLoading = false; return of(null); }), @@ -121,16 +171,16 @@ export class EbookReaderComponent implements OnInit, OnDestroy { this.destroy$.next(); this.destroy$.complete(); this.viewManager.destroy(); - this.bookmarkService.reset(); + this.annotationService.reset(); + this.progressService.endSession(); + this.progressService.reset(); + this.selectionService.reset(); + this.sidebarService.reset(); + this.leftSidebarService.reset(); + this.headerService.reset(); + this.noteService.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; @@ -164,14 +214,19 @@ export class EbookReaderComponent implements OnInit, OnDestroy { })), switchMap(({book, fileBlob}) => { this.book = book; - this.coverUpdatedOn = book.metadata?.coverUpdatedOn; const fileUrl = URL.createObjectURL(fileBlob); this._fileUrl = fileUrl; + this.progressService.initialize(this.bookId, book.bookType!); + this.selectionService.initialize(this.bookId, this.destroy$); + this.headerService.initialize(this.bookId, book.metadata?.title || '', this.destroy$); + return this.viewManager.loadEpub(fileUrl).pipe( tap(() => { this.applyStyles(); - this.chapters = this.viewManager.getChapters(); + this.sidebarService.initialize(this.bookId, book, this.destroy$); + this.leftSidebarService.initialize(this.bookId, this.destroy$); + this.noteService.initialize(this.bookId, this.destroy$); }), switchMap(() => this.viewManager.getMetadata()), switchMap(() => { @@ -186,15 +241,6 @@ export class EbookReaderComponent implements OnInit, OnDestroy { ); } - 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$)) @@ -208,13 +254,14 @@ export class EbookReaderComponent implements OnInit, OnDestroy { switch (event.type) { case 'load': this.applyStyles(); - this.chapters = this.viewManager.getChapters(); + this.sidebarService.updateChapters(); this.updateSectionFractions(); break; case 'relocate': if (this.relocateTimeout) clearTimeout(this.relocateTimeout); this.relocateTimeout = setTimeout(() => { - this.handleRelocateEvent(event.detail); + this.progressService.handleRelocateEvent(event.detail); + this.updateBookmarkIndicator(); }, 100); if (this.sectionFractionsTimeout) clearTimeout(this.sectionFractionsTimeout); @@ -225,6 +272,9 @@ export class EbookReaderComponent implements OnInit, OnDestroy { case 'middle-single-tap': this.toggleHeaderNavbarPinned(); break; + case 'text-selected': + this.selectionService.handleTextSelected(event.detail, event.popupPosition); + break; } }); } @@ -233,80 +283,15 @@ export class EbookReaderComponent implements OnInit, OnDestroy { 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 updateBookmarkIndicator(): void { + const currentCfi = this.progressService.currentCfi; + this.sidebarService.bookmarks$ + .pipe(takeUntil(this.destroy$)) + .subscribe(bookmarks => { + this.isCurrentCfiBookmarked = currentCfi + ? bookmarks.some(b => b.cfi === currentCfi) + : false; + }); } private applyStyles(): void { @@ -319,115 +304,12 @@ export class EbookReaderComponent implements OnInit, OnDestroy { } } - 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(); } @@ -446,4 +328,20 @@ export class EbookReaderComponent implements OnInit, OnDestroy { onWindowResize(event: Event): void { this.visibilityManager.updateWindowHeight(window.innerHeight); } + + handleSelectionAction(action: TextSelectionAction): void { + if (action.type === 'note') { + this.noteService.openNewNoteDialog(); + } else { + this.selectionService.handleAction(action); + } + } + + onNoteSave(result: NoteDialogResult): void { + this.noteService.saveNote(result); + } + + onNoteCancel(): void { + this.noteService.closeDialog(); + } } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation-renderer.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation-renderer.service.ts new file mode 100644 index 000000000..212f596b1 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation-renderer.service.ts @@ -0,0 +1,138 @@ +import { Injectable } from '@angular/core'; +import { defer, from, Observable, of } from 'rxjs'; +import { AnnotationStyle } from '../../../../../shared/service/annotation.service'; + +export type { AnnotationStyle }; + +export interface Annotation { + value: string; + color?: string; + style?: AnnotationStyle; +} + +@Injectable({ + providedIn: 'root' +}) +export class ReaderAnnotationService { + private annotationStyles = new Map(); + + addAnnotation(view: any, annotation: Annotation): Observable<{index: number; label: string} | undefined> { + if (!view) return of(undefined); + + const style = annotation.style || 'highlight'; + const color = annotation.color || '#FFFF00'; + + this.annotationStyles.set(annotation.value, {color, style}); + + return defer(() => from(view.addAnnotation({value: annotation.value}) as Promise<{index: number; label: string} | undefined>)); + } + + deleteAnnotation(view: any, cfi: string): Observable { + if (!view) return of(undefined); + + this.annotationStyles.delete(cfi); + + return defer(() => from(view.deleteAnnotation({value: cfi}) as Promise)); + } + + showAnnotation(view: any, cfi: string): Observable { + if (!view) return of(undefined); + + return defer(() => from(view.showAnnotation({value: cfi}) as Promise)); + } + + addAnnotations(view: any, annotations: Annotation[]): void { + annotations.forEach(annotation => { + const style = annotation.style || 'highlight'; + const color = annotation.color || '#FFFF00'; + this.annotationStyles.set(annotation.value, {color, style}); + view?.addAnnotation({value: annotation.value}); + }); + } + + getAnnotationStyle(cfi: string): { color: string; style: AnnotationStyle } | undefined { + return this.annotationStyles.get(cfi); + } + + getOverlayerDrawFunction(style: AnnotationStyle): (rects: DOMRectList, options: { color?: string }) => SVGElement { + const createSVGElement = (tag: string): SVGElement => + document.createElementNS('http://www.w3.org/2000/svg', tag); + + switch (style) { + case 'underline': + return (rects: DOMRectList, options: { color?: string; width?: number } = {}) => { + const {color = 'red', width: strokeWidth = 2} = options; + const g = createSVGElement('g'); + g.setAttribute('fill', color); + for (const {left, bottom, width} of Array.from(rects)) { + const el = createSVGElement('rect'); + el.setAttribute('x', String(left)); + el.setAttribute('y', String(bottom - strokeWidth)); + el.setAttribute('height', String(strokeWidth)); + el.setAttribute('width', String(width)); + g.append(el); + } + return g; + }; + + case 'strikethrough': + return (rects: DOMRectList, options: { color?: string; width?: number } = {}) => { + const {color = 'red', width: strokeWidth = 2} = options; + const g = createSVGElement('g'); + g.setAttribute('fill', color); + for (const {left, top, bottom, width} of Array.from(rects)) { + const el = createSVGElement('rect'); + el.setAttribute('x', String(left)); + el.setAttribute('y', String((top + bottom) / 2)); + el.setAttribute('height', String(strokeWidth)); + el.setAttribute('width', String(width)); + g.append(el); + } + return g; + }; + + case 'squiggly': + return (rects: DOMRectList, options: { color?: string; width?: number } = {}) => { + const {color = 'red', width: strokeWidth = 2} = options; + const g = createSVGElement('g'); + g.setAttribute('fill', 'none'); + g.setAttribute('stroke', color); + g.setAttribute('stroke-width', String(strokeWidth)); + const block = strokeWidth * 1.5; + for (const {left, bottom, width} of Array.from(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; + }; + + case 'highlight': + default: + return (rects: DOMRectList, options: { color?: string } = {}) => { + const {color = 'yellow'} = options; + const g = createSVGElement('g'); + g.setAttribute('fill', color); + (g as SVGElement).style.opacity = 'var(--overlayer-highlight-opacity, .3)'; + (g as SVGElement).style.mixBlendMode = 'var(--overlayer-highlight-blend-mode, multiply)'; + for (const {left, top, height, width} of Array.from(rects)) { + const el = createSVGElement('rect'); + el.setAttribute('x', String(left)); + el.setAttribute('y', String(top)); + el.setAttribute('height', String(height)); + el.setAttribute('width', String(width)); + g.append(el); + } + return g; + }; + } + } + + clearAnnotations(): void { + this.annotationStyles.clear(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation.service.ts new file mode 100644 index 000000000..db62592aa --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/features/annotations/annotation.service.ts @@ -0,0 +1,130 @@ +import {inject, Injectable} from '@angular/core'; +import {Observable, of} from 'rxjs'; +import {catchError, map, tap} from 'rxjs/operators'; +import {MessageService} from 'primeng/api'; +import { + Annotation, + AnnotationService, + AnnotationStyle, + CreateAnnotationRequest +} from '../../../../../shared/service/annotation.service'; +import {Annotation as ViewAnnotation} from './annotation-renderer.service'; + +@Injectable() +export class ReaderAnnotationHttpService { + private annotationService = inject(AnnotationService); + private messageService = inject(MessageService); + + private currentChapterTitle: string | null = null; + + updateCurrentChapter(chapterTitle: string): void { + this.currentChapterTitle = chapterTitle; + } + + createAnnotation( + bookId: number, + cfi: string, + text: string, + color: string = '#FFFF00', + style: AnnotationStyle = 'highlight', + note?: string + ): Observable { + const request: CreateAnnotationRequest = { + bookId, + cfi, + text, + color, + style, + note, + chapterTitle: this.currentChapterTitle || undefined + }; + + return this.annotationService.createAnnotation(request).pipe( + tap(() => { + this.messageService.add({ + severity: 'success', + summary: 'Highlight Added', + detail: 'Your highlight was saved successfully.' + }); + }), + catchError(error => { + const isDuplicate = error?.status === 409; + this.messageService.add( + isDuplicate + ? { + severity: 'warn', + summary: 'Highlight Already Exists', + detail: 'You already have a highlight at this location.' + } + : { + severity: 'error', + summary: 'Unable to Add Highlight', + detail: 'Something went wrong while adding the highlight. Please try again.' + } + ); + return of(null); + }) + ); + } + + getAnnotations(bookId: number): Observable { + return this.annotationService.getAnnotationsForBook(bookId).pipe( + catchError(() => { + return of([]); + }) + ); + } + + deleteAnnotation(annotationId: number): Observable { + return this.annotationService.deleteAnnotation(annotationId).pipe( + map(() => { + this.messageService.add({ + severity: 'success', + summary: 'Highlight Removed', + detail: 'Your highlight was removed successfully.' + }); + return true; + }), + catchError(() => { + this.messageService.add({ + severity: 'error', + summary: 'Unable to Remove Highlight', + detail: 'Something went wrong while removing the highlight. Please try again.' + }); + return of(false); + }) + ); + } + + updateAnnotationNote(annotationId: number, note: string): Observable { + return this.annotationService.updateAnnotation(annotationId, {note}).pipe( + tap(() => { + this.messageService.add({ + severity: 'success', + summary: 'Note Updated', + detail: 'Your note was saved successfully.' + }); + }), + catchError(() => { + this.messageService.add({ + severity: 'error', + summary: 'Unable to Update Note', + detail: 'Something went wrong while updating the note. Please try again.' + }); + return of(null); + }) + ); + } + + toViewAnnotations(annotations: Annotation[]): ViewAnnotation[] { + return annotations.map(a => ({ + value: a.cfi, + color: a.color, + style: a.style + })); + } + + reset(): void { + this.currentChapterTitle = null; + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-bookmark.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/features/bookmarks/bookmark.service.ts similarity index 91% rename from booklore-ui/src/app/features/readers/ebook-reader/services/reader-bookmark.service.ts rename to booklore-ui/src/app/features/readers/ebook-reader/features/bookmarks/bookmark.service.ts index fbec39dc6..bbdffda7a 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-bookmark.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/features/bookmarks/bookmark.service.ts @@ -1,7 +1,7 @@ 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 {BookMarkService} from '../../../../../shared/service/book-mark.service'; import {MessageService} from 'primeng/api'; @Injectable() @@ -23,7 +23,6 @@ export class ReaderBookmarkService { createBookmarkAtCurrentPosition(bookId: number): Observable { const cfi = this.currentCFI; if (!cfi) { - console.error('Could not get current CFI - please navigate to a page first'); return of(false); } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/services/epub-custom-font.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/features/fonts/custom-font.service.ts similarity index 95% rename from booklore-ui/src/app/features/readers/ebook-reader/services/epub-custom-font.service.ts rename to booklore-ui/src/app/features/readers/ebook-reader/features/fonts/custom-font.service.ts index 38fc78c31..a7d523b76 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/services/epub-custom-font.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/features/fonts/custom-font.service.ts @@ -1,6 +1,6 @@ import {Injectable, inject} from '@angular/core'; -import {CustomFontService} from '../../../../shared/service/custom-font.service'; -import {CustomFont} from '../../../../shared/model/custom-font.model'; +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'; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/features/notes/note.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/features/notes/note.service.ts new file mode 100644 index 000000000..0ea8e2c03 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/features/notes/note.service.ts @@ -0,0 +1,168 @@ +import {inject, Injectable} from '@angular/core'; +import {BehaviorSubject, Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; +import {MessageService} from 'primeng/api'; +import {BookNoteV2Service, CreateBookNoteV2Request, UpdateBookNoteV2Request} from '../../../../../shared/service/book-note-v2.service'; +import {NoteDialogData, NoteDialogResult} from '../../dialogs/note-dialog.component'; +import {ReaderSelectionService} from '../selection/selection.service'; +import {ReaderProgressService} from '../../state/progress.service'; +import {ReaderLeftSidebarService} from '../../layout/panel/panel.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; + +export interface NoteDialogState { + visible: boolean; + data: NoteDialogData | null; +} + +@Injectable() +export class ReaderNoteService { + private bookNoteV2Service = inject(BookNoteV2Service); + private messageService = inject(MessageService); + private selectionService = inject(ReaderSelectionService); + private progressService = inject(ReaderProgressService); + private leftSidebarService = inject(ReaderLeftSidebarService); + private viewManager = inject(ReaderViewManagerService); + + private bookId!: number; + private destroy$ = new Subject(); + + private dialogStateSubject = new BehaviorSubject({ + visible: false, + data: null + }); + public dialogState$ = this.dialogStateSubject.asObservable(); + + get showNoteDialog(): boolean { + return this.dialogStateSubject.value.visible; + } + + get noteDialogData(): NoteDialogData | null { + return this.dialogStateSubject.value.data; + } + + initialize(bookId: number, destroy$: Subject): void { + this.bookId = bookId; + this.destroy$ = destroy$; + + this.leftSidebarService.editNote$ + .pipe(takeUntil(this.destroy$)) + .subscribe(note => { + this.openEditDialog({ + cfi: note.cfi, + selectedText: note.selectedText, + chapterTitle: note.chapterTitle, + noteId: note.id, + noteContent: note.noteContent, + color: note.color + }); + }); + } + + openNewNoteDialog(): void { + const selectionData = this.selectionService.getCurrentSelection(); + if (selectionData) { + this.dialogStateSubject.next({ + visible: true, + data: { + cfi: selectionData.cfi, + selectedText: selectionData.text, + chapterTitle: this.progressService.currentChapterName || undefined + } + }); + this.selectionService.hidePopup(); + } + } + + openEditDialog(data: NoteDialogData): void { + this.dialogStateSubject.next({ + visible: true, + data + }); + } + + saveNote(result: NoteDialogResult): void { + const data = this.dialogStateSubject.value.data; + if (!data) return; + + if (data.noteId) { + this.updateNote(data.noteId, result); + } else { + this.createNote(data, result); + } + } + + private createNote(data: NoteDialogData, result: NoteDialogResult): void { + const createRequest: CreateBookNoteV2Request = { + bookId: this.bookId, + cfi: data.cfi, + selectedText: data.selectedText, + noteContent: result.noteContent, + color: result.color, + chapterTitle: data.chapterTitle + }; + + this.bookNoteV2Service.createNote(createRequest) + .pipe(takeUntil(this.destroy$)) + .subscribe({ + next: () => { + this.closeDialog(); + this.viewManager.clearSelection(); + this.leftSidebarService.refreshNotes(); + this.messageService.add({ + severity: 'success', + summary: 'Note Saved', + detail: 'Your note has been saved successfully.' + }); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Save Failed', + detail: 'Failed to save the note. Please try again.' + }); + } + }); + } + + private updateNote(noteId: number, result: NoteDialogResult): void { + const updateRequest: UpdateBookNoteV2Request = { + noteContent: result.noteContent, + color: result.color + }; + + this.bookNoteV2Service.updateNote(noteId, updateRequest) + .pipe(takeUntil(this.destroy$)) + .subscribe({ + next: () => { + this.closeDialog(); + this.leftSidebarService.refreshNotes(); + this.messageService.add({ + severity: 'success', + summary: 'Note Updated', + detail: 'Your note has been updated successfully.' + }); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Update Failed', + detail: 'Failed to update the note. Please try again.' + }); + } + }); + } + + closeDialog(): void { + this.dialogStateSubject.next({ + visible: false, + data: null + }); + } + + reset(): void { + this.dialogStateSubject.next({ + visible: false, + data: null + }); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/features/selection/selection.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/features/selection/selection.service.ts new file mode 100644 index 000000000..f35c49685 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/features/selection/selection.service.ts @@ -0,0 +1,266 @@ +import {inject, Injectable} from '@angular/core'; +import {Subject} from 'rxjs'; +import {switchMap, takeUntil, tap} from 'rxjs/operators'; +import {of} from 'rxjs'; +import {Annotation} from '../../../../../shared/service/annotation.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {ReaderAnnotationHttpService} from '../annotations/annotation.service'; +import {ReaderLeftSidebarService} from '../../layout/panel/panel.service'; +import {TextSelectionAction, AnnotationStyle} from '../../shared/selection-popup.component'; + +export interface SelectionState { + visible: boolean; + position: { x: number; y: number }; + showBelow: boolean; + overlappingAnnotationId: number | null; + selectedText: string; +} + +export interface SelectionDetail { + text: string; + cfi: string; + range: Range; + index: number; +} + +@Injectable() +export class ReaderSelectionService { + private viewManager = inject(ReaderViewManagerService); + private annotationService = inject(ReaderAnnotationHttpService); + private leftSidebarService = inject(ReaderLeftSidebarService); + + private bookId!: number; + private annotations: Annotation[] = []; + private currentSelection: SelectionDetail | null = null; + private destroy$ = new Subject(); + + private _visible = false; + private _position = { x: 0, y: 0 }; + private _showBelow = false; + private _overlappingAnnotationId: number | null = null; + + private previewCfi: string | null = null; + private previewColor: string | null = null; + private previewStyle: AnnotationStyle | null = null; + + private stateSubject = new Subject(); + public state$ = this.stateSubject.asObservable(); + + private annotationsChangedSubject = new Subject(); + public annotationsChanged$ = this.annotationsChangedSubject.asObservable(); + + get visible(): boolean { + return this._visible; + } + + get position(): { x: number; y: number } { + return this._position; + } + + get showBelow(): boolean { + return this._showBelow; + } + + get overlappingAnnotationId(): number | null { + return this._overlappingAnnotationId; + } + + initialize(bookId: number, destroy$: Subject): void { + this.bookId = bookId; + this.destroy$ = destroy$; + } + + setAnnotations(annotations: Annotation[]): void { + this.annotations = annotations; + } + + handleTextSelected(detail: SelectionDetail, popupPosition?: { x: number; y: number; showBelow?: boolean }): void { + this.currentSelection = detail; + this._overlappingAnnotationId = this.findOverlappingAnnotation(detail.cfi); + this._visible = true; + this._position = popupPosition || { x: 0, y: 0 }; + this._showBelow = popupPosition?.showBelow || false; + + this.emitState(); + } + + handleAction(action: TextSelectionAction): void { + if (action.type === 'preview' && this.currentSelection) { + this.updatePreview( + this.currentSelection.cfi, + action.color || '#FFFF00', + action.style || 'highlight' + ); + return; + } + + this._visible = false; + this._overlappingAnnotationId = null; + + if (action.type === 'dismiss') { + this.clearPreview(); + this.viewManager.clearSelection(); + this.currentSelection = null; + this.emitState(); + return; + } + + if (action.type === 'select') { + this.clearPreview(); + this.emitState(); + } else if (action.type === 'search' && action.searchText) { + this.clearPreview(); + this.viewManager.clearSelection(); + this.leftSidebarService.openWithSearch(action.searchText); + this.emitState(); + } else if (action.type === 'delete' && action.annotationId) { + this.clearPreview(); + this.deleteAnnotation(action.annotationId); + this.viewManager.clearSelection(); + } else if (action.type === 'annotate' && this.currentSelection) { + this.clearPreview(); + this.createAnnotation( + this.currentSelection.text, + this.currentSelection.cfi, + action.color || '#FFFF00', + action.style || 'highlight' + ); + } + + this.currentSelection = null; + this.emitState(); + } + + private updatePreview(cfi: string, color: string, style: AnnotationStyle): void { + if (this.previewCfi) { + this.viewManager.deleteAnnotation(this.previewCfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(); + } + + this.previewCfi = cfi; + this.previewColor = color; + this.previewStyle = style; + + this.viewManager.addAnnotation({ + value: cfi, + color: color, + style: style + }).pipe(takeUntil(this.destroy$)).subscribe(); + } + + private clearPreview(): void { + if (this.previewCfi) { + this.viewManager.deleteAnnotation(this.previewCfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(); + this.previewCfi = null; + this.previewColor = null; + this.previewStyle = null; + } + } + + private createAnnotation(text: string, cfi: string, color: string, style: AnnotationStyle): void { + this.annotationService.createAnnotation( + this.bookId, + cfi, + text, + color, + style + ).pipe( + switchMap(savedAnnotation => { + if (!savedAnnotation) return of(null); + + this.annotations = [...this.annotations, savedAnnotation]; + this.annotationsChangedSubject.next(this.annotations); + + return this.viewManager.addAnnotation({ + value: savedAnnotation.cfi, + color: savedAnnotation.color, + style: savedAnnotation.style + }).pipe( + tap(() => this.viewManager.clearSelection()) + ); + }), + takeUntil(this.destroy$) + ).subscribe(); + } + + deleteAnnotation(annotationId: number): void { + const annotation = this.annotations.find(a => a.id === annotationId); + if (!annotation) return; + + this.annotationService.deleteAnnotation(annotationId) + .pipe(takeUntil(this.destroy$)) + .subscribe(success => { + if (success) { + this.viewManager.deleteAnnotation(annotation.cfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(); + this.annotations = this.annotations.filter(a => a.id !== annotationId); + this.annotationsChangedSubject.next(this.annotations); + } + }); + } + + private findOverlappingAnnotation(selectionCfi: string): number | null { + if (!selectionCfi || !this.annotations.length) { + return null; + } + + const getBasePath = (cfi: string): string => { + const inner = cfi.replace(/^epubcfi\(/, '').replace(/\)$/, ''); + const commaIndex = inner.indexOf(','); + if (commaIndex > 0) { + return inner.substring(0, commaIndex).replace(/:\d+$/, ''); + } + return inner.replace(/:\d+$/, ''); + }; + + const selectionBasePath = getBasePath(selectionCfi); + + for (const annotation of this.annotations) { + const annotationBasePath = getBasePath(annotation.cfi); + if (selectionBasePath.startsWith(annotationBasePath) || + annotationBasePath.startsWith(selectionBasePath) || + selectionBasePath === annotationBasePath) { + return annotation.id; + } + } + + return null; + } + + private emitState(): void { + this.stateSubject.next({ + visible: this._visible, + position: this._position, + showBelow: this._showBelow, + overlappingAnnotationId: this._overlappingAnnotationId, + selectedText: this.currentSelection?.text || '' + }); + } + + reset(): void { + this._visible = false; + this._position = { x: 0, y: 0 }; + this._showBelow = false; + this._overlappingAnnotationId = null; + this.currentSelection = null; + this.annotations = []; + this.previewCfi = null; + this.previewColor = null; + this.previewStyle = null; + } + + getCurrentSelection(): SelectionDetail | null { + return this.currentSelection; + } + + hidePopup(): void { + this._visible = false; + this._overlappingAnnotationId = null; + this.clearPreview(); + this.emitState(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/index.ts b/booklore-ui/src/app/features/readers/ebook-reader/index.ts new file mode 100644 index 000000000..e4bc65970 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/index.ts @@ -0,0 +1,35 @@ +export * from './ebook-reader.component'; + +export * from './core/loader.service'; +export * from './core/view-manager.service'; +export * from './core/event.service'; +export * from './core/style.service'; + +export * from './state/reader-state.service'; +export * from './state/progress.service'; +export * from './state/themes.constant'; + +export * from './features/annotations/annotation.service'; +export * from './features/annotations/annotation-renderer.service'; +export * from './features/bookmarks/bookmark.service'; +export * from './features/notes/note.service'; +export * from './features/selection/selection.service'; +export * from './features/fonts/custom-font.service'; + +export * from './layout/header/header.component'; +export * from './layout/header/header.service'; +export * from './layout/header/quick-settings.component'; +export * from './layout/footer/footer.component'; +export * from './layout/sidebar/sidebar.component'; +export * from './layout/sidebar/sidebar.service'; +export * from './layout/panel/panel.component'; +export * from './layout/panel/panel.service'; + +export * from './dialogs/settings-dialog.component'; +export * from './dialogs/metadata-dialog.component'; +export * from './dialogs/note-dialog.component'; + +export * from './shared/icon.component'; +export * from './shared/selection-popup.component'; +export * from './shared/visibility.util'; +export * from './shared/header-footer.util'; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.html b/booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.html similarity index 69% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.html rename to booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.html index 5d98e23a4..5083701f1 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.html +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.html @@ -1,11 +1,6 @@ -
- -
@@ -23,20 +18,20 @@ (input)="onProgressChange($event)" title="Progress"/>
- @for (frac of sectionFractions; track frac) { + @for (frac of displaySectionFractions; track frac) { }
-
@if (showLocationPopover) { -
+
@@ -72,19 +67,19 @@
-
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.scss new file mode 100644 index 000000000..c37962ae7 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.scss @@ -0,0 +1,359 @@ +// Variables matching sidebar styling +$navbar-bg: #1a1a1a; +$text-primary: rgba(255, 255, 255, 0.95); +$text-secondary: rgba(255, 255, 255, 0.6); +$text-muted: rgba(255, 255, 255, 0.4); +$border-color: rgba(255, 255, 255, 0.08); +$hover-bg: rgba(255, 255, 255, 0.08); +$active-color: #818cf8; +$transition-fast: 150ms ease; +$transition-normal: 200ms ease; + +.reader-navbar { + position: absolute; + bottom: 0; + left: 0; + right: 0; + height: 48px; + padding: 0 12px; + display: flex; + align-items: center; + gap: 8px; + z-index: 1000; + background: $navbar-bg; + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + border-top: 1px solid $border-color; + box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.3); + color: $text-primary; + opacity: 0; + pointer-events: none; + transform: translateY(100%); + transition: opacity 250ms cubic-bezier(0.4, 0, 0.2, 1), + transform 250ms cubic-bezier(0.4, 0, 0.2, 1); + + &.visible { + opacity: 1; + pointer-events: auto; + transform: translateY(0); + } +} + +.icon-btn { + background: none; + border: none; + color: $text-secondary; + cursor: pointer; + padding: 8px; + border-radius: 8px; + transition: background $transition-fast, color $transition-fast; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + + svg { + display: block; + } + + &:hover:not(:disabled) { + background: $hover-bg; + color: $text-primary; + } + + &:disabled { + opacity: 0.3; + cursor: not-allowed; + } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 2px; + } +} + +.progress-section { + flex: 1; + display: flex; + align-items: center; + gap: 12px; + + .location-btn { + background: rgba(255, 255, 255, 0.05); + border: 1px solid $border-color; + color: $text-primary; + padding: 6px 14px; + border-radius: 6px; + cursor: pointer; + font-size: 13px; + font-weight: 500; + transition: background $transition-fast, border-color $transition-fast; + font-variant-numeric: tabular-nums; + + &:hover { + background: $hover-bg; + border-color: rgba(255, 255, 255, 0.15); + } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 2px; + } + } + + .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.12); + position: relative; + z-index: 1; + cursor: pointer; + + &::-webkit-slider-thumb { + -webkit-appearance: none; + width: 16px; + height: 16px; + border-radius: 50%; + background: $active-color; + cursor: pointer; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); + transition: transform $transition-fast, box-shadow $transition-fast; + + &:hover { + transform: scale(1.1); + box-shadow: 0 2px 8px rgba(129, 140, 248, 0.4); + } + } + + &::-moz-range-thumb { + width: 16px; + height: 16px; + border-radius: 50%; + background: $active-color; + cursor: pointer; + border: none; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); + } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 4px; + } + } + + .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.4); + border-radius: 2px; + } + } +} + +.location-popover { + position: absolute; + bottom: 60px; + left: 50%; + transform: translateX(-50%); + background: $navbar-bg; + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + border: 1px solid $border-color; + border-radius: 12px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5); + z-index: 1001; + min-width: 380px; + animation: popoverSlideIn 200ms cubic-bezier(0.4, 0, 0.2, 1); + color: $text-primary; + + .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: $text-muted; + text-transform: uppercase; + letter-spacing: 0.5px; + font-weight: 600; + } + + .value { + font-size: 20px; + font-weight: 600; + letter-spacing: -0.3px; + color: $text-primary; + } + } + + .separator { + width: 1px; + height: 44px; + background: $border-color; + } + } + + .divider { + height: 1px; + background: $border-color; + margin: 16px 0; + } + + .location-controls { + display: flex; + flex-direction: column; + gap: 12px; + padding: 4px 0; + + .control-row { + display: flex; + align-items: center; + gap: 16px; + + label { + min-width: 70px; + font-size: 13px; + font-weight: 500; + color: $text-secondary; + } + + input { + width: 65px; + padding: 6px 10px; + background: rgba(255, 255, 255, 0.05); + border: 1px solid $border-color; + border-radius: 6px; + color: $text-primary; + font-size: 13px; + text-align: right; + transition: background $transition-fast, border-color $transition-fast; + font-variant-numeric: tabular-nums; + + &:focus { + outline: none; + background: $hover-bg; + border-color: $active-color; + } + } + + span { + font-size: 13px; + color: $text-secondary; + } + } + } + + .section-navigation { + display: flex; + gap: 8px; + justify-content: center; + align-items: center; + + .nav-btn { + background: none; + border: none; + color: $text-secondary; + padding: 0; + margin: 0; + border-radius: 8px; + cursor: pointer; + transition: background $transition-fast, color $transition-fast, transform $transition-fast; + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + + svg { + display: block; + } + + &:hover { + background: $hover-bg; + color: $text-primary; + } + + &:active { + transform: scale(0.95); + } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 2px; + } + } + } +} + +@keyframes popoverSlideIn { + from { + opacity: 0; + transform: translateX(-50%) translateY(8px); + } + to { + opacity: 1; + transform: translateX(-50%) translateY(0); + } +} + +@media (max-width: 600px) { + .reader-navbar { + padding: 0 8px; + height: 44px; + } + + .location-popover { + min-width: 320px; + left: 16px; + right: 16px; + transform: none; + + @keyframes popoverSlideIn { + from { + opacity: 0; + transform: translateY(8px); + } + to { + opacity: 1; + transform: translateY(0); + } + } + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.ts similarity index 82% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.ts rename to booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.ts index 92c06c4a2..f92693ed7 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/footer/footer.component.ts @@ -1,5 +1,6 @@ import {Component, EventEmitter, HostListener, inject, Input, Output} from '@angular/core'; -import {ReaderViewManagerService} from '../../services/reader-view-manager.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {ReaderIconComponent} from '../../shared/icon.component'; interface TocItem { label: string; @@ -29,13 +30,21 @@ interface RelocateEventDetail { @Component({ selector: 'app-reader-navbar', standalone: true, - templateUrl: './reader-navbar.component.html', - styleUrls: ['./reader-navbar.component.scss'] + imports: [ReaderIconComponent], + templateUrl: './footer.component.html', + styleUrls: ['./footer.component.scss'] }) export class ReaderNavbarComponent { @Input() progressData: RelocateEventDetail | null = null; @Input() forceVisible = false; - @Input() sectionFractions: number[] = []; + @Input() set sectionFractions(value: number[]) { + this._sectionFractions = value.filter(f => f > 0.001 && f < 0.999); + } + private _sectionFractions: number[] = []; + + get displaySectionFractions(): number[] { + return this._sectionFractions; + } @Output() progressChange = new EventEmitter(); private managerService = inject(ReaderViewManagerService); @@ -103,6 +112,16 @@ export class ReaderNavbarComponent { return this.forceVisible; } + get canGoPrevious(): boolean { + const s = this.progressData?.section; + return !!s && s.current > 0; + } + + get canGoNext(): boolean { + const s = this.progressData?.section; + return !!s && s.current < s.total - 1; + } + onProgressChange(event: Event) { const target = event.target as HTMLInputElement; const fraction = parseFloat(target.value) / 100; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html new file mode 100644 index 000000000..32802c2ca --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html @@ -0,0 +1,18 @@ +
+ + + {{ bookTitle }} + + + +
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.scss similarity index 100% rename from booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.scss rename to booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.scss diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts new file mode 100644 index 000000000..4cbf5600b --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts @@ -0,0 +1,58 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; +import {ReaderHeaderService} from './header.service'; +import {ReaderIconComponent} from '../../shared/icon.component'; + +@Component({ + selector: 'app-reader-header', + standalone: true, + imports: [ReaderIconComponent], + templateUrl: './header.component.html', + styleUrls: ['./header.component.scss'] +}) +export class ReaderHeaderComponent implements OnInit, OnDestroy { + private headerService = inject(ReaderHeaderService); + private destroy$ = new Subject(); + + isVisible = false; + + get bookTitle(): string { + return this.headerService.title; + } + + get currentTheme() { + return this.headerService.currentState.theme; + } + + ngOnInit(): void { + this.headerService.forceVisible$ + .pipe(takeUntil(this.destroy$)) + .subscribe(visible => this.isVisible = visible); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + onShowChapters(): void { + this.headerService.openSidebar(); + } + + onOpenSearch(): void { + this.headerService.openLeftSidebar('search'); + } + + onCreateBookmark(): void { + this.headerService.createBookmark(); + } + + onShowControls(): void { + this.headerService.openControls(); + } + + onClose(): void { + this.headerService.close(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts new file mode 100644 index 000000000..95cd0438e --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts @@ -0,0 +1,134 @@ +import {inject, Injectable} from '@angular/core'; +import {Location} from '@angular/common'; +import {BehaviorSubject, Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; +import {ReaderStateService} from '../../state/reader-state.service'; +import {ReaderSidebarService} from '../sidebar/sidebar.service'; +import {ReaderLeftSidebarService} from '../panel/panel.service'; +import {BookService} from '../../../../book/service/book.service'; +import {EbookViewerSetting} from '../../../../book/model/book.model'; + +@Injectable() +export class ReaderHeaderService { + private stateService = inject(ReaderStateService); + private sidebarService = inject(ReaderSidebarService); + private leftSidebarService = inject(ReaderLeftSidebarService); + private bookService = inject(BookService); + private location = inject(Location); + + private destroy$ = new Subject(); + private bookId!: number; + private bookTitle = ''; + + private _forceVisible = new BehaviorSubject(false); + forceVisible$ = this._forceVisible.asObservable(); + + private _showControls = new Subject(); + private _showMetadata = new Subject(); + showControls$ = this._showControls.asObservable(); + showMetadata$ = this._showMetadata.asObservable(); + + get currentState() { + return this.stateService.currentState; + } + + get title(): string { + return this.bookTitle; + } + + get isVisible(): boolean { + return this._forceVisible.value; + } + + initialize(bookId: number, title: string, destroy$: Subject): void { + this.bookId = bookId; + this.bookTitle = title; + this.destroy$ = destroy$; + } + + setForceVisible(visible: boolean): void { + this._forceVisible.next(visible); + } + + openSidebar(): void { + this.sidebarService.open(); + } + + openLeftSidebar(tab?: 'search' | 'notes'): void { + this.leftSidebarService.open(tab); + } + + createBookmark(): void { + this.sidebarService.createBookmark(); + } + + openControls(): void { + this._showControls.next(); + } + + openMetadata(): void { + this._showMetadata.next(); + } + + close(): void { + this.location.back(); + } + + toggleDarkMode(): void { + this.stateService.toggleDarkMode(); + this.syncSettingsToBackend(); + } + + increaseFontSize(): void { + this.stateService.updateFontSize(1); + this.syncSettingsToBackend(); + } + + decreaseFontSize(): void { + this.stateService.updateFontSize(-1); + this.syncSettingsToBackend(); + } + + increaseLineHeight(): void { + this.stateService.updateLineHeight(0.1); + this.syncSettingsToBackend(); + } + + decreaseLineHeight(): void { + this.stateService.updateLineHeight(-0.1); + this.syncSettingsToBackend(); + } + + setFlow(flow: 'paginated' | 'scrolled'): void { + this.stateService.setFlow(flow); + this.syncSettingsToBackend(); + } + + private syncSettingsToBackend(): void { + const state = this.stateService.currentState; + const setting: EbookViewerSetting = { + lineHeight: state.lineHeight, + justify: state.justify, + hyphenate: state.hyphenate, + maxColumnCount: state.maxColumnCount, + gap: state.gap, + fontSize: state.fontSize, + theme: typeof state.theme === 'object' && 'name' in state.theme + ? state.theme.name + : (state.theme as any), + maxInlineSize: state.maxInlineSize, + maxBlockSize: state.maxBlockSize, + fontFamily: state.fontFamily, + isDark: state.isDark, + flow: state.flow, + }; + this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId) + .pipe(takeUntil(this.destroy$)) + .subscribe(); + } + + reset(): void { + this._forceVisible.next(false); + this.bookTitle = ''; + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.html b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.html new file mode 100644 index 000000000..7c21d3b2c --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.html @@ -0,0 +1,53 @@ +
+
+
+

Quick Settings

+ +
+ +
+ +
+ +
+ ☀️ + + 🌙 +
+
+ + +
+ +
+
+ + {{ state.fontSize }}% + +
+
+
+ + +
+ +
+
+ + {{ state.lineHeight | number:'1.1-1' }} + +
+
+
+
+ + +
+
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.scss new file mode 100644 index 000000000..432bc70f9 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.scss @@ -0,0 +1,260 @@ +// Variables matching sidebar/dialog styling +$dialog-bg: #1a1a1a; +$text-primary: rgba(255, 255, 255, 0.95); +$text-secondary: rgba(255, 255, 255, 0.6); +$text-muted: rgba(255, 255, 255, 0.4); +$border-color: rgba(255, 255, 255, 0.08); +$hover-bg: rgba(255, 255, 255, 0.08); +$active-color: #818cf8; +$active-bg: rgba(129, 140, 248, 0.15); +$transition-fast: 150ms ease; +$transition-normal: 200ms ease; + +.dialog-overlay { + position: fixed; + inset: 0; + z-index: 12000; + animation: fadeIn $transition-normal; +} + +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +.dialog { + position: absolute; + top: 44px; + right: 24px; + width: 280px; + background: $dialog-bg; + border: 1px solid $border-color; + border-radius: 12px; + box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5); + animation: slideDown 200ms cubic-bezier(0.4, 0, 0.2, 1); + overflow: hidden; +} + +@keyframes slideDown { + from { + transform: translateY(-8px); + opacity: 0; + } + to { + transform: translateY(0); + opacity: 1; + } +} + +.dialog-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 16px; + border-bottom: 1px solid $border-color; + background: rgba(0, 0, 0, 0.2); +} + +.dialog-title { + font-size: 14px; + font-weight: 600; + color: $text-primary; + margin: 0; +} + +.close-btn { + background: none; + border: none; + color: $text-muted; + font-size: 16px; + cursor: pointer; + padding: 4px; + border-radius: 6px; + transition: background $transition-fast, color $transition-fast; + line-height: 1; + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + + &:hover { + background: $hover-bg; + color: $text-primary; + } +} + +.dialog-body { + padding: 16px; +} + +.control { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 0; + + &:not(:last-child) { + border-bottom: 1px solid $border-color; + } + + > label { + color: $text-primary; + font-size: 13px; + font-weight: 500; + flex-shrink: 0; + } +} + +.control-right { + display: flex; + align-items: center; + gap: 8px; +} + +// Mode icons for dark/light mode +.mode-icon { + font-size: 14px; + opacity: 0.3; + transition: all 300ms 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%); + } + } +} + +// Toggle switch +.switch { + position: relative; + width: 40px; + height: 22px; + background: rgba(255, 255, 255, 0.15); + border: none; + border-radius: 11px; + cursor: pointer; + transition: background 300ms ease; + padding: 0; + + &.active { + background: $active-color; + + .slider { + transform: translateX(18px); + } + } + + .slider { + position: absolute; + top: 2px; + left: 2px; + width: 18px; + height: 18px; + background: #ffffff; + border-radius: 50%; + transition: transform 300ms ease; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + } + + &:hover { + background: rgba(255, 255, 255, 0.2); + + &.active { + background: #9aa3fa; + } + } +} + +// Stepper control +.stepper { + display: flex; + align-items: center; + gap: 2px; + background: rgba(255, 255, 255, 0.03); + padding: 2px; + border-radius: 6px; + border: 1px solid $border-color; + + button { + width: 26px; + height: 26px; + background: rgba(255, 255, 255, 0.05); + color: $text-secondary; + border: none; + border-radius: 4px; + cursor: pointer; + font-size: 14px; + display: flex; + align-items: center; + justify-content: center; + transition: all $transition-fast; + font-weight: 300; + + &:hover { + background: $hover-bg; + color: $text-primary; + } + + &:active { + transform: scale(0.95); + } + } + + span { + min-width: 50px; + text-align: center; + color: $text-primary; + font-size: 12px; + font-weight: 500; + font-variant-numeric: tabular-nums; + } +} + +.dialog-footer { + padding: 12px 16px; + border-top: 1px solid $border-color; + background: rgba(0, 0, 0, 0.15); +} + +.more-settings-btn { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + width: 100%; + padding: 10px 16px; + background: rgba(255, 255, 255, 0.05); + border: 1px solid $border-color; + border-radius: 8px; + color: $text-primary; + font-size: 13px; + font-weight: 500; + cursor: pointer; + transition: all $transition-fast; + + &:hover { + background: $hover-bg; + border-color: rgba(255, 255, 255, 0.15); + } + + &:active { + transform: scale(0.98); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.ts new file mode 100644 index 000000000..362848cc1 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/quick-settings.component.ts @@ -0,0 +1,84 @@ +import {Component, EventEmitter, Input, Output} from '@angular/core'; +import {DecimalPipe} from '@angular/common'; +import {ReaderStateService} from '../../state/reader-state.service'; +import {ReaderIconComponent} from '../../shared/icon.component'; +import {BookService} from '../../../../book/service/book.service'; +import {EbookViewerSetting} from '../../../../book/model/book.model'; + +@Component({ + selector: 'app-reader-quick-settings', + standalone: true, + imports: [DecimalPipe, ReaderIconComponent], + templateUrl: './quick-settings.component.html', + styleUrls: ['./quick-settings.component.scss'] +}) +export class ReaderQuickSettingsComponent { + @Input() stateService!: ReaderStateService; + @Input() bookId!: number; + @Output() close = new EventEmitter(); + @Output() openFullSettings = new EventEmitter(); + + constructor(private bookService: BookService) {} + + get state() { + return this.stateService.currentState; + } + + get isDarkMode(): boolean { + return this.state.isDark; + } + + private syncSettingsToBackend(): void { + 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(); + } + + toggleDarkMode(): void { + this.stateService.toggleDarkMode(); + this.syncSettingsToBackend(); + } + + increaseFontSize(): void { + this.stateService.updateFontSize(1); + this.syncSettingsToBackend(); + } + + decreaseFontSize(): void { + this.stateService.updateFontSize(-1); + this.syncSettingsToBackend(); + } + + increaseLineHeight(): void { + this.stateService.updateLineHeight(0.1); + this.syncSettingsToBackend(); + } + + decreaseLineHeight(): void { + this.stateService.updateLineHeight(-0.1); + this.syncSettingsToBackend(); + } + + onOpenFullSettings(): void { + this.close.emit(); + this.openFullSettings.emit(); + } + + onOverlayClick(event: MouseEvent): void { + if ((event.target as HTMLElement).classList.contains('quick-settings-overlay')) { + this.close.emit(); + } + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.html b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.html new file mode 100644 index 000000000..31fbc4480 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.html @@ -0,0 +1,171 @@ +@if (isOpen) { + +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.scss new file mode 100644 index 000000000..119949232 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.scss @@ -0,0 +1,524 @@ +// Variables +$sidebar-width: 320px; +$sidebar-bg: #1a1a1a; +$text-primary: rgba(255, 255, 255, 0.95); +$text-secondary: rgba(255, 255, 255, 0.6); +$text-muted: rgba(255, 255, 255, 0.4); +$border-color: rgba(255, 255, 255, 0.08); +$hover-bg: rgba(255, 255, 255, 0.06); +$active-bg: rgba(99, 102, 241, 0.15); +$active-color: #818cf8; +$transition-fast: 150ms ease; +$transition-normal: 200ms ease; + +// Overlay +.sidebar-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.4); + backdrop-filter: blur(1px); + z-index: 12000; + animation: fadeIn $transition-normal; + + &.closing { + animation: fadeOut $transition-normal forwards; + } +} + +// Sidebar container - positioned on the RIGHT +.sidebar { + position: fixed; + top: 0; + right: 0; + bottom: 0; + width: $sidebar-width; + background: $sidebar-bg; + display: flex; + flex-direction: column; + color: $text-primary; + box-shadow: -4px 0 24px rgba(0, 0, 0, 0.3); + animation: slideInRight 250ms cubic-bezier(0.4, 0, 0.2, 1); + z-index: 12001; + + &.closing { + animation: slideOutRight 200ms cubic-bezier(0.4, 0, 0.2, 1) forwards; + } +} + +// Header +.sidebar-header { + display: flex; + align-items: center; + padding: 20px 16px; + border-bottom: 1px solid $border-color; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.03) 0%, transparent 100%); +} + +.sidebar-title { + font-size: 16px; + font-weight: 600; + margin: 0; + color: $text-primary; +} + +// Tabs +.tabs { + display: flex; + border-bottom: 1px solid $border-color; + background: rgba(0, 0, 0, 0.2); +} + +.tab { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: 12px 8px; + background: none; + border: none; + color: $text-secondary; + font-size: 11px; + font-weight: 500; + cursor: pointer; + transition: color $transition-fast, background $transition-fast; + position: relative; + + &:hover { + color: $text-primary; + background: $hover-bg; + } + + &.active { + color: $active-color; + + &::after { + content: ''; + position: absolute; + bottom: 0; + left: 16px; + right: 16px; + height: 2px; + background: $active-color; + border-radius: 1px 1px 0 0; + } + } +} + +.tab-icon { + width: 18px; + height: 18px; +} + +.badge { + position: absolute; + top: 6px; + right: calc(50% - 20px); + min-width: 16px; + height: 16px; + padding: 0 4px; + background: $active-color; + color: white; + font-size: 10px; + font-weight: 600; + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; +} + +// Content area +.content { + flex: 1; + overflow-y: auto; + overscroll-behavior: contain; + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background: transparent; + } + + &::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.15); + border-radius: 3px; + + &:hover { + background: rgba(255, 255, 255, 0.25); + } + } +} + +// Item list +.item-list { + list-style: none; + margin: 0; + padding: 8px 0; +} + +.list-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 16px; + cursor: pointer; + transition: background $transition-fast; + + &:hover { + background: $hover-bg; + + .delete-btn { + opacity: 1; + } + } +} + +.item-content { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +// Notes +.notes-container { + display: flex; + flex-direction: column; + height: 100%; +} + +.notes-search-wrapper { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + background: rgba(0, 0, 0, 0.2); + border-bottom: 1px solid $border-color; + + .search-icon { + color: $text-muted; + flex-shrink: 0; + } + + .search-input { + flex: 1; + background: none; + border: none; + color: $text-primary; + font-size: 14px; + outline: none; + + &::placeholder { + color: $text-muted; + } + } + + .clear-btn { + width: 24px; + height: 24px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.1); + border: none; + border-radius: 50%; + color: $text-secondary; + cursor: pointer; + transition: background $transition-fast, color $transition-fast; + flex-shrink: 0; + + &:hover { + background: rgba(255, 255, 255, 0.15); + color: $text-primary; + } + } +} + +.note-item { + align-items: flex-start; + + &:hover .action-buttons { + opacity: 1; + } +} + +.note-bar { + width: 3px; + align-self: stretch; + border-radius: 2px; + flex-shrink: 0; +} + +.note-text { + font-size: 13px; + color: $text-primary; + line-height: 1.4; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + overflow: hidden; +} + +.note-selected-text { + font-size: 12px; + font-style: italic; + color: $text-secondary; + line-height: 1.4; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; +} + +.action-buttons { + display: flex; + flex-direction: column; + gap: 4px; + opacity: 0; + transition: opacity $transition-fast; +} + +.edit-btn { + width: 28px; + height: 28px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + background: none; + border: none; + border-radius: 6px; + color: $text-muted; + cursor: pointer; + transition: background $transition-fast, color $transition-fast; + flex-shrink: 0; + + svg { + width: 16px; + height: 16px; + } + + &:hover { + background: rgba(99, 102, 241, 0.15); + color: $active-color; + } +} + +.item-chapter { + font-size: 11px; + color: $text-secondary; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.item-meta { + font-size: 11px; + color: $text-muted; +} + +.delete-btn { + width: 28px; + height: 28px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + background: none; + border: none; + border-radius: 6px; + color: $text-muted; + cursor: pointer; + opacity: 0; + transition: opacity $transition-fast, background $transition-fast, color $transition-fast; + flex-shrink: 0; + + svg { + width: 16px; + height: 16px; + } + + &:hover { + background: rgba(239, 68, 68, 0.15); + color: #ef4444; + } +} + +// Empty state +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 48px 24px; + text-align: center; + color: $text-secondary; +} + +.empty-icon { + width: 48px; + height: 48px; + margin-bottom: 16px; + opacity: 0.4; +} + +.empty-state p { + margin: 0 0 8px; + font-size: 14px; + font-weight: 500; +} + +.empty-hint { + font-size: 12px; + color: $text-muted; +} + +// Search +.search-container { + display: flex; + flex-direction: column; + height: 100%; +} + +.search-input-wrapper { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + background: rgba(0, 0, 0, 0.2); + border-bottom: 1px solid $border-color; + + .search-icon { + color: $text-muted; + flex-shrink: 0; + } + + .search-input { + flex: 1; + background: none; + border: none; + color: $text-primary; + font-size: 14px; + outline: none; + + &::placeholder { + color: $text-muted; + } + } + + .clear-btn { + width: 24px; + height: 24px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.1); + border: none; + border-radius: 50%; + color: $text-secondary; + cursor: pointer; + transition: background $transition-fast, color $transition-fast; + flex-shrink: 0; + + &:hover { + background: rgba(255, 255, 255, 0.15); + color: $text-primary; + } + } +} + +.search-progress { + padding: 12px 16px; + display: flex; + flex-direction: column; + gap: 8px; + + .progress-bar { + height: 3px; + background: rgba(255, 255, 255, 0.1); + border-radius: 2px; + overflow: hidden; + + .progress-fill { + height: 100%; + background: $active-color; + border-radius: 2px; + transition: width 200ms ease-out; + } + } + + .progress-text { + font-size: 11px; + color: $text-muted; + text-align: center; + } +} + +.search-results-header { + padding: 10px 16px; + font-size: 11px; + font-weight: 600; + color: $text-secondary; + text-transform: uppercase; + letter-spacing: 0.5px; + border-bottom: 1px solid $border-color; +} + +.search-results { + flex: 1; + overflow-y: auto; +} + +.search-result-item { + .item-content { + gap: 6px; + } +} + +.search-excerpt { + font-size: 13px; + color: $text-secondary; + line-height: 1.5; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + overflow: hidden; + + .excerpt-context { + color: $text-secondary; + } + + .excerpt-match { + background: rgba(255, 255, 0, 0.25); + color: $text-primary; + font-weight: 500; + padding: 1px 2px; + border-radius: 2px; + } +} + +// Animations +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes fadeOut { + from { opacity: 1; } + to { opacity: 0; } +} + +@keyframes slideInRight { + from { transform: translateX(100%); } + to { transform: translateX(0); } +} + +@keyframes slideOutRight { + from { transform: translateX(0); } + to { transform: translateX(100%); } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.ts new file mode 100644 index 000000000..299b2eaee --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.component.ts @@ -0,0 +1,131 @@ +import {Component, EventEmitter, inject, OnDestroy, OnInit, Output} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {FormsModule} from '@angular/forms'; +import {Subject} from 'rxjs'; +import {takeUntil, debounceTime, distinctUntilChanged, filter} from 'rxjs/operators'; +import {ReaderLeftSidebarService, LeftSidebarTab} from './panel.service'; +import {BookNoteV2} from '../../../../../shared/service/book-note-v2.service'; +import {SearchState, SearchResult} from '../sidebar/sidebar.service'; +import {ReaderIconComponent} from '../../shared/icon.component'; + +@Component({ + selector: 'app-reader-left-sidebar', + standalone: true, + templateUrl: './panel.component.html', + styleUrls: ['./panel.component.scss'], + imports: [CommonModule, FormsModule, ReaderIconComponent] +}) +export class ReaderLeftSidebarComponent implements OnInit, OnDestroy { + private leftSidebarService = inject(ReaderLeftSidebarService); + private destroy$ = new Subject(); + + isOpen = false; + closing = false; + activeTab: LeftSidebarTab = 'search'; + notes: BookNoteV2[] = []; + notesSearchQuery = ''; + searchState: SearchState = { query: '', results: [], isSearching: false, progress: 0 }; + searchQuery = ''; + private searchInput$ = new Subject(); + + ngOnInit(): void { + this.leftSidebarService.isOpen$ + .pipe(takeUntil(this.destroy$)) + .subscribe(isOpen => { + if (isOpen) { + this.isOpen = true; + this.closing = false; + } else if (this.isOpen) { + this.closeWithAnimation(); + } + }); + + this.leftSidebarService.activeTab$ + .pipe(takeUntil(this.destroy$)) + .subscribe(tab => this.activeTab = tab); + + this.leftSidebarService.notes$ + .pipe(takeUntil(this.destroy$)) + .subscribe(notes => this.notes = notes); + + this.leftSidebarService.searchState$ + .pipe(takeUntil(this.destroy$)) + .subscribe(state => { + this.searchState = state; + if (state.query && state.query !== this.searchQuery) { + this.searchQuery = state.query; + } + }); + + this.searchInput$ + .pipe( + debounceTime(500), + distinctUntilChanged(), + filter(query => query.length >= 3 || query.length === 0), + takeUntil(this.destroy$) + ) + .subscribe(query => this.leftSidebarService.search(query)); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private closeWithAnimation(): void { + this.closing = true; + setTimeout(() => { + this.isOpen = false; + this.closing = false; + }, 250); + } + + onOverlayClick(): void { + this.leftSidebarService.close(); + } + + setActiveTab(tab: LeftSidebarTab): void { + this.leftSidebarService.setActiveTab(tab); + } + + onNoteClick(cfi: string): void { + this.leftSidebarService.navigateToNote(cfi); + } + + onEditNote(event: MouseEvent, note: BookNoteV2): void { + event.stopPropagation(); + this.leftSidebarService.editNote(note); + } + + onDeleteNote(event: MouseEvent, noteId: number): void { + event.stopPropagation(); + this.leftSidebarService.deleteNote(noteId); + } + + onNotesSearchInput(query: string): void { + this.notesSearchQuery = query; + this.leftSidebarService.setNotesSearchQuery(query); + } + + clearNotesSearch(): void { + this.notesSearchQuery = ''; + this.leftSidebarService.setNotesSearchQuery(''); + } + + get filteredNotes(): BookNoteV2[] { + return this.leftSidebarService.getFilteredNotes(); + } + + onSearchInput(query: string): void { + this.searchInput$.next(query); + } + + onSearchResultClick(cfi: string): void { + this.leftSidebarService.navigateToSearchResult(cfi); + } + + clearSearch(): void { + this.searchQuery = ''; + this.leftSidebarService.clearSearch(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.service.ts new file mode 100644 index 000000000..2eaab9611 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/panel/panel.service.ts @@ -0,0 +1,204 @@ +import {inject, Injectable} from '@angular/core'; +import {BehaviorSubject, Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; +import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {SearchResult, SearchState} from '../sidebar/sidebar.service'; + +export type LeftSidebarTab = 'search' | 'notes'; + +@Injectable() +export class ReaderLeftSidebarService { + private viewManager = inject(ReaderViewManagerService); + private bookNoteV2Service = inject(BookNoteV2Service); + + private destroy$ = new Subject(); + private bookId!: number; + + private _isOpen = new BehaviorSubject(false); + private _activeTab = new BehaviorSubject('search'); + private _notes = new BehaviorSubject([]); + private _notesSearchQuery = new BehaviorSubject(''); + private _searchState = new BehaviorSubject({ + query: '', + results: [], + isSearching: false, + progress: 0 + }); + private searchAbortController: AbortController | null = null; + + isOpen$ = this._isOpen.asObservable(); + activeTab$ = this._activeTab.asObservable(); + notes$ = this._notes.asObservable(); + notesSearchQuery$ = this._notesSearchQuery.asObservable(); + searchState$ = this._searchState.asObservable(); + + private _editNote = new Subject(); + editNote$ = this._editNote.asObservable(); + + initialize(bookId: number, destroy$: Subject): void { + this.bookId = bookId; + this.destroy$ = destroy$; + + this.loadNotes(); + } + + private loadNotes(): void { + this.bookNoteV2Service.getNotesForBook(this.bookId) + .pipe(takeUntil(this.destroy$)) + .subscribe(notes => this._notes.next(notes)); + } + + refreshNotes(): void { + this.loadNotes(); + } + + open(tab?: LeftSidebarTab): void { + if (tab) { + this._activeTab.next(tab); + } + this._isOpen.next(true); + } + + close(): void { + this._isOpen.next(false); + } + + setActiveTab(tab: LeftSidebarTab): void { + this._activeTab.next(tab); + } + + openWithSearch(query: string): void { + this._activeTab.next('search'); + this._isOpen.next(true); + setTimeout(() => this.search(query), 100); + } + + navigateToNote(cfi: string): void { + this.viewManager.goTo(cfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.close()); + } + + deleteNote(noteId: number): void { + this.bookNoteV2Service.deleteNote(noteId) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => { + const updatedNotes = this._notes.value.filter(n => n.id !== noteId); + this._notes.next(updatedNotes); + }); + } + + editNote(note: BookNoteV2): void { + this.close(); + this._editNote.next(note); + } + + setNotesSearchQuery(query: string): void { + this._notesSearchQuery.next(query); + } + + getFilteredNotes(): BookNoteV2[] { + const query = this._notesSearchQuery.value.toLowerCase().trim(); + if (!query) { + return this._notes.value; + } + return this._notes.value.filter(note => + note.noteContent.toLowerCase().includes(query) || + (note.selectedText?.toLowerCase().includes(query)) || + (note.chapterTitle?.toLowerCase().includes(query)) + ); + } + + async search(query: string): Promise { + if (!query.trim()) { + this.clearSearch(); + return; + } + + if (this.searchAbortController) { + this.searchAbortController.abort(); + } + this.searchAbortController = new AbortController(); + + this._searchState.next({ + query, + results: [], + isSearching: true, + progress: 0 + }); + + try { + const results: SearchResult[] = []; + const searchGenerator = this.viewManager.search({ query }); + + for await (const result of searchGenerator) { + if (this.searchAbortController?.signal.aborted) break; + + if (typeof result === 'string' && result === 'done') { + break; + } + + if ('progress' in result) { + this._searchState.next({ + ...this._searchState.value, + progress: result.progress + }); + } + + if ('subitems' in result && result.subitems) { + const sectionResults = result.subitems.map((item: any) => ({ + cfi: item.cfi, + excerpt: item.excerpt, + sectionLabel: result.label + })); + results.push(...sectionResults); + this._searchState.next({ + ...this._searchState.value, + results: [...results] + }); + } + } + + this._searchState.next({ + query, + results, + isSearching: false, + progress: 1 + }); + } catch (error) { + this._searchState.next({ + ...this._searchState.value, + isSearching: false + }); + } + } + + clearSearch(): void { + if (this.searchAbortController) { + this.searchAbortController.abort(); + this.searchAbortController = null; + } + this.viewManager.clearSearch(); + this._searchState.next({ + query: '', + results: [], + isSearching: false, + progress: 0 + }); + } + + navigateToSearchResult(cfi: string): void { + this.viewManager.goTo(cfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.close()); + } + + reset(): void { + this._isOpen.next(false); + this._activeTab.next('search'); + this._notes.next([]); + this._notesSearchQuery.next(''); + this.clearSearch(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.html b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.html new file mode 100644 index 000000000..ede94553e --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.html @@ -0,0 +1,150 @@ +@if (isOpen) { + +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.scss new file mode 100644 index 000000000..529b38f1c --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.scss @@ -0,0 +1,552 @@ +// Variables +$sidebar-width: 300px; +$sidebar-bg: #1a1a1a; +$text-primary: rgba(255, 255, 255, 0.95); +$text-secondary: rgba(255, 255, 255, 0.6); +$text-muted: rgba(255, 255, 255, 0.4); +$border-color: rgba(255, 255, 255, 0.08); +$hover-bg: rgba(255, 255, 255, 0.06); +$active-bg: rgba(99, 102, 241, 0.15); +$active-color: #818cf8; +$transition-fast: 150ms ease; +$transition-normal: 200ms ease; + +// Overlay +.sidebar-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.4); + backdrop-filter: blur(2px); + z-index: 12000; + animation: fadeIn $transition-normal; + + &.closing { + animation: fadeOut $transition-normal forwards; + } +} + +// Sidebar container +.sidebar { + position: fixed; + top: 0; + left: 0; + bottom: 0; + width: $sidebar-width; + background: $sidebar-bg; + display: flex; + flex-direction: column; + color: $text-primary; + box-shadow: 4px 0 24px rgba(0, 0, 0, 0.3); + animation: slideIn 250ms cubic-bezier(0.4, 0, 0.2, 1); + z-index: 12001; + + &.closing { + animation: slideOut 200ms cubic-bezier(0.4, 0, 0.2, 1) forwards; + } +} + +// Header +.sidebar-header { + display: flex; + gap: 14px; + padding: 20px 16px; + border-bottom: 1px solid $border-color; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.03) 0%, transparent 100%); +} + +.book-cover { + width: 60px; + height: 90px; + object-fit: cover; + border-radius: 4px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + flex-shrink: 0; + cursor: pointer; + transition: transform $transition-fast, box-shadow $transition-fast; + + &:hover { + transform: scale(1.03); + box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4); + } + + &:focus-visible { + outline: 2px solid $active-color; + outline-offset: 2px; + } +} + +.book-meta { + display: flex; + flex-direction: column; + justify-content: center; + min-width: 0; + gap: 6px; +} + +.book-title { + font-size: 14px; + font-weight: 600; + line-height: 1.3; + margin: 0; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; +} + +.book-authors { + font-size: 12px; + color: $text-secondary; + margin: 0; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 1; + overflow: hidden; +} + +// Tabs +.tabs { + display: flex; + border-bottom: 1px solid $border-color; + background: rgba(0, 0, 0, 0.2); +} + +.tab { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; + padding: 12px 8px; + background: none; + border: none; + color: $text-secondary; + font-size: 11px; + font-weight: 500; + cursor: pointer; + transition: color $transition-fast, background $transition-fast; + position: relative; + + &:hover { + color: $text-primary; + background: $hover-bg; + } + + &.active { + color: $active-color; + + &::after { + content: ''; + position: absolute; + bottom: 0; + left: 16px; + right: 16px; + height: 2px; + background: $active-color; + border-radius: 1px 1px 0 0; + } + } +} + +.tab-icon { + width: 18px; + height: 18px; +} + +.badge { + position: absolute; + top: 6px; + right: calc(50% - 20px); + min-width: 16px; + height: 16px; + padding: 0 4px; + background: $active-color; + color: white; + font-size: 10px; + font-weight: 600; + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; +} + +// Content area +.content { + flex: 1; + overflow-y: auto; + overscroll-behavior: contain; + + &::-webkit-scrollbar { + width: 6px; + } + + &::-webkit-scrollbar-track { + background: transparent; + } + + &::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.15); + border-radius: 3px; + + &:hover { + background: rgba(255, 255, 255, 0.25); + } + } +} + +// Chapter list +.chapter-list, +.subchapter-list { + list-style: none; + margin: 0; + padding: 8px 0; +} + +.subchapter-list { + padding: 0; +} + +.chapter-row { + display: flex; + align-items: center; + width: 100%; + padding: 10px 16px; + padding-left: calc(16px + var(--depth, 0) * 16px); + background: none; + border: none; + color: $text-primary; + font-size: 13px; + text-align: left; + cursor: pointer; + transition: background $transition-fast; + + &:hover { + background: $hover-bg; + } + + &.active { + background: $active-bg; + color: $active-color; + font-weight: 500; + } + + &.expandable { + font-weight: 500; + } +} + +.chapter-label { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.expand-icon { + width: 16px; + height: 16px; + flex-shrink: 0; + margin-left: 8px; + color: $text-muted; + transition: transform $transition-fast; + + &.expanded { + transform: rotate(90deg); + } +} + +// Item list (bookmarks & highlights) +.item-list { + list-style: none; + margin: 0; + padding: 8px 0; +} + +.list-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 16px; + cursor: pointer; + transition: background $transition-fast; + + &:hover { + background: $hover-bg; + + .delete-btn { + opacity: 1; + } + } +} + +.highlight-item { + align-items: flex-start; +} + +.highlight-bar { + width: 3px; + align-self: stretch; + border-radius: 2px; + flex-shrink: 0; +} + +.item-content { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.item-title { + font-size: 13px; + font-weight: 500; + color: $text-primary; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.highlight-text { + font-size: 13px; + font-style: italic; + color: $text-primary; + line-height: 1.4; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + overflow: hidden; +} + +.item-chapter { + font-size: 11px; + color: $text-secondary; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.item-meta { + font-size: 11px; + color: $text-muted; +} + +.action-buttons { + display: flex; + flex-direction: column; + gap: 4px; + opacity: 0; + transition: opacity $transition-fast; + flex-shrink: 0; +} + +.list-item:hover .action-buttons { + opacity: 1; +} + +.edit-btn, +.delete-btn { + width: 28px; + height: 28px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + background: none; + border: none; + border-radius: 6px; + color: $text-muted; + cursor: pointer; + transition: background $transition-fast, color $transition-fast; + flex-shrink: 0; + + svg { + width: 16px; + height: 16px; + } +} + +.edit-btn:hover { + background: rgba(99, 102, 241, 0.15); + color: $active-color; +} + +.delete-btn:hover { + background: rgba(239, 68, 68, 0.15); + color: #ef4444; +} + +// Empty state +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 48px 24px; + text-align: center; + color: $text-secondary; +} + +.empty-icon { + width: 48px; + height: 48px; + margin-bottom: 16px; + opacity: 0.4; +} + +.empty-state p { + margin: 0 0 8px; + font-size: 14px; + font-weight: 500; +} + +.empty-hint { + font-size: 12px; + color: $text-muted; +} + +// Search +.search-container { + display: flex; + flex-direction: column; + height: 100%; +} + +.search-input-wrapper { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + background: rgba(0, 0, 0, 0.2); + border-bottom: 1px solid $border-color; + + .search-icon { + color: $text-muted; + flex-shrink: 0; + } + + .search-input { + flex: 1; + background: none; + border: none; + color: $text-primary; + font-size: 14px; + outline: none; + + &::placeholder { + color: $text-muted; + } + } + + .clear-btn { + width: 24px; + height: 24px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.1); + border: none; + border-radius: 50%; + color: $text-secondary; + cursor: pointer; + transition: background $transition-fast, color $transition-fast; + flex-shrink: 0; + + &:hover { + background: rgba(255, 255, 255, 0.15); + color: $text-primary; + } + } +} + +.search-progress { + padding: 12px 16px; + display: flex; + flex-direction: column; + gap: 8px; + + .progress-bar { + height: 3px; + background: rgba(255, 255, 255, 0.1); + border-radius: 2px; + overflow: hidden; + + .progress-fill { + height: 100%; + background: $active-color; + border-radius: 2px; + transition: width 200ms ease-out; + } + } + + .progress-text { + font-size: 11px; + color: $text-muted; + text-align: center; + } +} + +.search-results-header { + padding: 10px 16px; + font-size: 11px; + font-weight: 600; + color: $text-secondary; + text-transform: uppercase; + letter-spacing: 0.5px; + border-bottom: 1px solid $border-color; +} + +.search-results { + flex: 1; + overflow-y: auto; +} + +.search-result-item { + .item-content { + gap: 6px; + } +} + +.search-excerpt { + font-size: 13px; + color: $text-secondary; + line-height: 1.5; + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + overflow: hidden; + + .excerpt-context { + color: $text-secondary; + } + + .excerpt-match { + background: rgba(255, 255, 0, 0.25); + color: $text-primary; + font-weight: 500; + padding: 1px 2px; + border-radius: 2px; + } +} + +// Animations +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes fadeOut { + from { opacity: 1; } + to { opacity: 0; } +} + +@keyframes slideIn { + from { transform: translateX(-100%); } + to { transform: translateX(0); } +} + +@keyframes slideOut { + from { transform: translateX(0); } + to { transform: translateX(-100%); } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.ts new file mode 100644 index 000000000..e992c82da --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.component.ts @@ -0,0 +1,122 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {FormsModule} from '@angular/forms'; +import {Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; +import {ReaderSidebarService, SidebarBookInfo, SidebarTab} from './sidebar.service'; +import {TocItem} from 'epubjs'; +import {BookMark} from '../../../../../shared/service/book-mark.service'; +import {Annotation} from '../../../../../shared/service/annotation.service'; +import {ReaderIconComponent} from '../../shared/icon.component'; + +@Component({ + selector: 'app-reader-sidebar', + standalone: true, + templateUrl: './sidebar.component.html', + styleUrls: ['./sidebar.component.scss'], + imports: [CommonModule, FormsModule, ReaderIconComponent] +}) +export class ReaderSidebarComponent implements OnInit, OnDestroy { + private sidebarService = inject(ReaderSidebarService); + private destroy$ = new Subject(); + + isOpen = false; + closing = false; + activeTab: SidebarTab = 'chapters'; + bookInfo: SidebarBookInfo = { id: null, title: '', authors: '', coverUrl: null }; + chapters: TocItem[] = []; + bookmarks: BookMark[] = []; + annotations: Annotation[] = []; + + ngOnInit(): void { + this.sidebarService.isOpen$ + .pipe(takeUntil(this.destroy$)) + .subscribe(isOpen => { + if (isOpen) { + this.isOpen = true; + this.closing = false; + } else if (this.isOpen) { + this.closeWithAnimation(); + } + }); + + this.sidebarService.activeTab$ + .pipe(takeUntil(this.destroy$)) + .subscribe(tab => this.activeTab = tab); + + this.sidebarService.bookInfo$ + .pipe(takeUntil(this.destroy$)) + .subscribe(info => this.bookInfo = info); + + this.sidebarService.chapters$ + .pipe(takeUntil(this.destroy$)) + .subscribe(chapters => this.chapters = chapters); + + this.sidebarService.bookmarks$ + .pipe(takeUntil(this.destroy$)) + .subscribe(bookmarks => this.bookmarks = bookmarks); + + this.sidebarService.annotations$ + .pipe(takeUntil(this.destroy$)) + .subscribe(annotations => this.annotations = annotations); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private closeWithAnimation(): void { + this.closing = true; + setTimeout(() => { + this.isOpen = false; + this.closing = false; + }, 250); + } + + onOverlayClick(): void { + this.sidebarService.close(); + } + + setActiveTab(tab: SidebarTab): void { + this.sidebarService.setActiveTab(tab); + } + + onChapterClick(chapter: TocItem): void { + if (chapter.subitems?.length) { + this.sidebarService.toggleChapterExpand(chapter.href); + } else { + this.sidebarService.navigateToChapter(chapter.href); + } + } + + isChapterExpanded(href: string): boolean { + return this.sidebarService.isChapterExpanded(href); + } + + isChapterActive(href: string): boolean { + return this.sidebarService.isChapterActive(href); + } + + onBookmarkClick(cfi: string): void { + this.sidebarService.navigateToBookmark(cfi); + } + + onDeleteBookmark(event: MouseEvent, bookmarkId: number): void { + event.stopPropagation(); + this.sidebarService.deleteBookmark(bookmarkId); + } + + onAnnotationClick(cfi: string): void { + this.sidebarService.navigateToAnnotation(cfi); + } + + onDeleteAnnotation(event: MouseEvent, annotationId: number): void { + event.stopPropagation(); + this.sidebarService.deleteAnnotation(annotationId); + } + + onCoverClick(): void { + this.sidebarService.openMetadata(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts new file mode 100644 index 000000000..486996b9a --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts @@ -0,0 +1,284 @@ +import {inject, Injectable, Injector} from '@angular/core'; +import {BehaviorSubject, Subject} from 'rxjs'; +import {takeUntil} from 'rxjs/operators'; +import {TocItem} from 'epubjs'; +import {BookMark, BookMarkService} from '../../../../../shared/service/book-mark.service'; +import {Annotation} from '../../../../../shared/service/annotation.service'; +import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; +import {ReaderViewManagerService} from '../../core/view-manager.service'; +import {ReaderProgressService} from '../../state/progress.service'; +import {ReaderBookmarkService} from '../../features/bookmarks/bookmark.service'; +import {ReaderAnnotationHttpService} from '../../features/annotations/annotation.service'; +import {ReaderSelectionService} from '../../features/selection/selection.service'; +import {Book} from '../../../../book/model/book.model'; + +export interface SidebarBookInfo { + id: number | null; + title: string; + authors: string; + coverUrl: string | null; +} + +export type SidebarTab = 'chapters' | 'bookmarks' | 'highlights'; + +export interface SearchResult { + cfi: string; + excerpt: { + pre: string; + match: string; + post: string; + }; + sectionLabel?: string; +} + +export interface SearchState { + query: string; + results: SearchResult[]; + isSearching: boolean; + progress: number; +} + +@Injectable() +export class ReaderSidebarService { + private injector = inject(Injector); + private urlHelper = inject(UrlHelperService); + private viewManager = inject(ReaderViewManagerService); + private progressService = inject(ReaderProgressService); + private bookmarkService = inject(ReaderBookmarkService); + private bookMarkHttpService = inject(BookMarkService); + private annotationService = inject(ReaderAnnotationHttpService); + + private destroy$ = new Subject(); + private bookId!: number; + private selectionService: ReaderSelectionService | null = null; + + private _isOpen = new BehaviorSubject(false); + private _activeTab = new BehaviorSubject('chapters'); + private _bookInfo = new BehaviorSubject({ + id: null, + title: '', + authors: '', + coverUrl: null + }); + private _chapters = new BehaviorSubject([]); + private _bookmarks = new BehaviorSubject([]); + private _annotations = new BehaviorSubject([]); + private _expandedChapters = new Set(); + + isOpen$ = this._isOpen.asObservable(); + activeTab$ = this._activeTab.asObservable(); + bookInfo$ = this._bookInfo.asObservable(); + chapters$ = this._chapters.asObservable(); + bookmarks$ = this._bookmarks.asObservable(); + annotations$ = this._annotations.asObservable(); + + private _showMetadata = new Subject(); + showMetadata$ = this._showMetadata.asObservable(); + + get currentChapterHref(): string | null { + return this.progressService.currentChapterHref; + } + + get activeTab(): SidebarTab { + return this._activeTab.value; + } + + initialize(bookId: number, book: Book, destroy$: Subject): void { + this.bookId = bookId; + this.destroy$ = destroy$; + + this._bookInfo.next({ + id: book.id, + title: book.metadata?.title || '', + authors: (book.metadata?.authors || []).join(', '), + coverUrl: this.urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn) + }); + + this._chapters.next(this.viewManager.getChapters()); + + this.loadBookmarks(); + + this.loadAnnotations(); + + this.subscribeToAnnotationChanges(); + } + + private subscribeToAnnotationChanges(): void { + if (!this.selectionService) { + this.selectionService = this.injector.get(ReaderSelectionService); + } + + this.selectionService.annotationsChanged$ + .pipe(takeUntil(this.destroy$)) + .subscribe(annotations => { + this._annotations.next(annotations); + }); + } + + private loadAnnotations(): void { + this.annotationService.getAnnotations(this.bookId) + .pipe(takeUntil(this.destroy$)) + .subscribe(annotations => { + this._annotations.next(annotations); + if (!this.selectionService) { + this.selectionService = this.injector.get(ReaderSelectionService); + } + this.selectionService.setAnnotations(annotations); + if (annotations.length > 0) { + const viewAnnotations = this.annotationService.toViewAnnotations(annotations); + this.viewManager.addAnnotations(viewAnnotations); + } + }); + } + + setAnnotations(annotations: Annotation[]): void { + this._annotations.next(annotations); + } + + updateChapters(): void { + this._chapters.next(this.viewManager.getChapters()); + } + + open(tab?: SidebarTab): void { + if (tab) { + this._activeTab.next(tab); + } + this._isOpen.next(true); + this.autoExpandCurrentChapter(); + } + + close(): void { + this._isOpen.next(false); + } + + setActiveTab(tab: SidebarTab): void { + this._activeTab.next(tab); + } + + navigateToChapter(href: string): void { + this.viewManager.goTo(href) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.close()); + } + + toggleChapterExpand(href: string): void { + 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 { + const currentHref = this.currentChapterHref; + if (!currentHref) return false; + + const normalizedItemHref = href.split('#')[0].replace(/^\//, ''); + const normalizedCurrentHref = currentHref.split('#')[0].replace(/^\//, ''); + + return normalizedItemHref === normalizedCurrentHref || href === currentHref; + } + + private autoExpandCurrentChapter(): void { + const currentHref = this.currentChapterHref; + if (!currentHref) return; + + const chapters = this._chapters.value; + 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 = currentHref.split('#')[0].replace(/^\//, ''); + + if (normalizedItemHref === normalizedCurrentHref || item.href === currentHref) { + parents.forEach(parentHref => this._expandedChapters.add(parentHref)); + return true; + } + + if (item.subitems?.length) { + if (expandParents(item.subitems, currentParents)) { + return true; + } + } + } + return false; + }; + + expandParents(chapters); + } + + private loadBookmarks(): void { + this.bookMarkHttpService.getBookmarksForBook(this.bookId) + .pipe(takeUntil(this.destroy$)) + .subscribe(bookmarks => this._bookmarks.next(bookmarks)); + } + + navigateToBookmark(cfi: string): void { + this.viewManager.goTo(cfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.close()); + } + + createBookmark(): void { + this.bookmarkService.createBookmarkAtCurrentPosition(this.bookId) + .pipe(takeUntil(this.destroy$)) + .subscribe(success => { + if (success) { + this.loadBookmarks(); + } + }); + } + + deleteBookmark(bookmarkId: number): void { + this.bookMarkHttpService.deleteBookmark(bookmarkId) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.loadBookmarks()); + } + + navigateToAnnotation(cfi: string): void { + this.viewManager.goTo(cfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(() => this.close()); + } + + deleteAnnotation(annotationId: number): void { + const annotations = this._annotations.value; + const annotation = annotations.find(a => a.id === annotationId); + if (!annotation) return; + + this.annotationService.deleteAnnotation(annotationId) + .pipe(takeUntil(this.destroy$)) + .subscribe(success => { + if (success) { + this.viewManager.deleteAnnotation(annotation.cfi) + .pipe(takeUntil(this.destroy$)) + .subscribe(); + const updatedAnnotations = annotations.filter(a => a.id !== annotationId); + this._annotations.next(updatedAnnotations); + if (this.selectionService) { + this.selectionService.setAnnotations(updatedAnnotations); + } + } + }); + } + + openMetadata(): void { + this.close(); + this._showMetadata.next(); + } + + reset(): void { + this._isOpen.next(false); + this._activeTab.next('chapters'); + this._bookInfo.next({ id: null, title: '', authors: '', coverUrl: null }); + this._chapters.next([]); + this._bookmarks.next([]); + this._annotations.next([]); + this._expandedChapters.clear(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.html b/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.html deleted file mode 100644 index a0ea13c81..000000000 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.html +++ /dev/null @@ -1,19 +0,0 @@ -
- - - {{ bookTitle || '' }} - - -
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.ts deleted file mode 100644 index 5edbfb418..000000000 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/header/reader-header.component.ts +++ /dev/null @@ -1,32 +0,0 @@ -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(); - @Output() showControls = new EventEmitter(); - @Output() showMetadata = new EventEmitter(); - @Output() createBookmark = new EventEmitter(); - @Output() close = new EventEmitter(); - @Output() toggleDarkMode = new EventEmitter(); - @Output() increaseFontSize = new EventEmitter(); - @Output() decreaseFontSize = new EventEmitter(); - @Output() increaseLineHeight = new EventEmitter(); - @Output() decreaseLineHeight = new EventEmitter(); - @Output() setFlow = new EventEmitter<'paginated' | 'scrolled'>(); - - get headerVisible(): boolean { - return this.forceVisible; - } -} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.scss deleted file mode 100644 index c58257c67..000000000 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/navbar/reader-navbar.component.scss +++ /dev/null @@ -1,301 +0,0 @@ -.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); - } -} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.html b/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.html deleted file mode 100644 index 729e0c0a6..000000000 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.html +++ /dev/null @@ -1,104 +0,0 @@ -
- -
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.scss deleted file mode 100644 index 922e8c886..000000000 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.scss +++ /dev/null @@ -1,416 +0,0 @@ -.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; - } -} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.ts deleted file mode 100644 index 88285697f..000000000 --- a/booklore-ui/src/app/features/readers/ebook-reader/reader-layout/sidebar/reader-sidebar.component.ts +++ /dev/null @@ -1,127 +0,0 @@ -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(); - @Output() chapterClick = new EventEmitter(); - @Output() bookmarkClick = new EventEmitter(); - @Output() deleteBookmark = new EventEmitter(); - @Output() coverClick = new EventEmitter(); - - private urlHelperService = inject(UrlHelperService); - - activeTab: 'chapters' | 'bookmarks' | 'annotation' = 'chapters'; - closing = false; - bookCoverUrl: string | null = null; - - expandedChapters = new Set(); - - 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; - } -} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/utils/reader-header-footer.util.ts b/booklore-ui/src/app/features/readers/ebook-reader/shared/header-footer.util.ts similarity index 99% rename from booklore-ui/src/app/features/readers/ebook-reader/utils/reader-header-footer.util.ts rename to booklore-ui/src/app/features/readers/ebook-reader/shared/header-footer.util.ts index 2e65086c6..179762baa 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/utils/reader-header-footer.util.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/shared/header-footer.util.ts @@ -8,7 +8,7 @@ export interface ThemeInfo { bg: string; } -export class ReaderHeaderFooterUtil { +export class PageDecorator { private static readonly DEFAULT_FONT_SIZE = '0.875rem'; static updateHeadersAndFooters(renderer: any, chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void { diff --git a/booklore-ui/src/app/features/readers/ebook-reader/shared/icon.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/shared/icon.component.ts new file mode 100644 index 000000000..a74f447f6 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/shared/icon.component.ts @@ -0,0 +1,169 @@ +import {Component, Input} from '@angular/core'; +import {CommonModule} from '@angular/common'; + +export type ReaderIconName = + | 'menu' + | 'close' + | 'chevron-left' + | 'chevron-right' + | 'chevron-down' + | 'chevron-first' + | 'chevron-last' + | 'dots-vertical' + | 'bookmark' + | 'settings' + | 'book' + | 'edit' + | 'copy' + | 'trash' + | 'search' + | 'note' + | 'plus' + | 'minus'; + +interface IconPath { + d: string; + type?: 'path' | 'polyline' | 'line' | 'rect' | 'circle'; +} + +const ICONS: Record = { + // Navigation icons + 'menu': [ + {d: 'M3,6 L21,6', type: 'line'}, + {d: 'M3,12 L21,12', type: 'line'}, + {d: 'M3,18 L21,18', type: 'line'} + ], + 'close': [ + {d: 'M18,6 L6,18', type: 'line'}, + {d: 'M6,6 L18,18', type: 'line'} + ], + 'chevron-left': [ + {d: '15,18 9,12 15,6', type: 'polyline'} + ], + 'chevron-right': [ + {d: '9,18 15,12 9,6', type: 'polyline'} + ], + 'chevron-down': [ + {d: '6,9 12,15 18,9', type: 'polyline'} + ], + 'chevron-first': [ + {d: '11,17 6,12 11,7', type: 'polyline'}, + {d: '18,17 13,12 18,7', type: 'polyline'} + ], + 'chevron-last': [ + {d: '13,17 18,12 13,7', type: 'polyline'}, + {d: '6,17 11,12 6,7', type: 'polyline'} + ], + 'dots-vertical': [ + {d: 'M12,12 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'}, + {d: 'M12,5 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'}, + {d: 'M12,19 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'} + ], + + // Action icons + 'bookmark': [ + {d: 'M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z'} + ], + 'settings': [ + {d: 'M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0', type: 'path'}, + {d: 'M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z'} + ], + 'book': [ + {d: 'M4 19.5A2.5 2.5 0 0 1 6.5 17H20'}, + {d: 'M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z'} + ], + 'edit': [ + {d: 'M12 20h9'}, + {d: 'M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z'} + ], + 'copy': [ + {d: 'M9,9 L22,9 L22,22 L9,22 Z M9,9 Q9,9 9,9', type: 'path'}, + {d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1'} + ], + 'trash': [ + {d: 'M3 6h18'}, + {d: 'M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6'}, + {d: 'M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'} + ], + 'search': [ + {d: 'M11 11m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0', type: 'path'}, + {d: 'M21 21l-4.35-4.35'} + ], + 'note': [ + {d: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'}, + {d: '14,2 14,8 20,8', type: 'polyline'}, + {d: 'M16 13H8'}, + {d: 'M16 17H8'}, + {d: 'M10 9H8'} + ], + 'plus': [ + {d: 'M12,5 L12,19', type: 'line'}, + {d: 'M5,12 L19,12', type: 'line'} + ], + 'minus': [ + {d: 'M5,12 L19,12', type: 'line'} + ] +}; + +@Component({ + selector: 'app-reader-icon', + standalone: true, + imports: [CommonModule], + template: ` + + @for (path of paths; track $index) { + @switch (path.type) { + @case ('line') { + + } + @case ('polyline') { + + } + @default { + + } + } + } + + `, + styles: [` + :host { + display: inline-flex; + align-items: center; + justify-content: center; + } + + svg { + display: block; + } + `] +}) +export class ReaderIconComponent { + @Input() name!: ReaderIconName; + @Input() size: number | string = 18; + @Input() strokeWidth: number | string = 2; + @Input() className = ''; + + get paths(): IconPath[] { + return ICONS[this.name] || []; + } + + getLineCoords(d: string, index: number): string { + // Parse "M3,6 L21,6" or "3,6 21,6" format + const coords = d.replace(/[ML]/g, ' ').trim().split(/[\s,]+/); + return coords[index] || '0'; + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.html b/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.html new file mode 100644 index 000000000..292e716e8 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.html @@ -0,0 +1,71 @@ +@if (visible) { + +
+ + + +
+ + + +
+ +
+ + + @if (showAnnotationOptions) { +
+
+ @for (style of styles; track style.value) { + + } +
+
+ @for (color of colors; track color.value) { + + } +
+
+ } +
+ +
+ + + + @if (overlappingAnnotationId) { +
+ + } +
+} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.scss new file mode 100644 index 000000000..5fae5419d --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.scss @@ -0,0 +1,233 @@ +.popup-backdrop { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 99998; + background: transparent; +} + +.text-selection-popup { + position: fixed; + display: flex; + align-items: center; + gap: 4px; + padding: 6px 8px; + background: linear-gradient(180deg, #2d3139 0%, #252830 100%); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3), 0 0 1px rgba(0, 0, 0, 0.2); + z-index: 99999; + transform: translateX(-50%); + animation: popupFadeIn 0.15s ease-out; + + &.show-below { + animation: popupFadeInBelow 0.15s ease-out; + } +} + +@keyframes popupFadeIn { + from { + opacity: 0; + transform: translateX(-50%) translateY(4px); + } + to { + opacity: 1; + transform: translateX(-50%) translateY(0); + } +} + +@keyframes popupFadeInBelow { + from { + opacity: 0; + transform: translateX(-50%) translateY(-4px); + } + to { + opacity: 1; + transform: translateX(-50%) translateY(0); + } +} + +.action-btn { + display: flex; + align-items: center; + justify-content: center; + gap: 2px; + width: 32px; + height: 32px; + padding: 0; + border: none; + border-radius: 6px; + background: transparent; + color: rgba(255, 255, 255, 0.8); + cursor: pointer; + transition: all 0.15s ease; + + &:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; + } + + &.active { + background: rgba(255, 255, 255, 0.12); + color: #fff; + } + + svg { + flex-shrink: 0; + } + + .chevron { + margin-left: -2px; + transition: transform 0.2s ease; + + &.open { + transform: rotate(180deg); + } + } +} + +.delete-btn { + &:hover { + background: rgba(239, 68, 68, 0.15); + color: #ef4444; + } +} + +.divider { + width: 1px; + height: 20px; + background: rgba(255, 255, 255, 0.1); + margin: 0 2px; +} + +.annotation-container { + position: relative; +} + +.annotation-options { + position: absolute; + left: 50%; + transform: translateX(-50%); + padding: 8px; + background: linear-gradient(180deg, #2d3139 0%, #252830 100%); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); + z-index: 100000; + display: flex; + flex-direction: column; + gap: 8px; + + &.above { + bottom: calc(100% + 8px); + animation: slideUp 0.15s ease-out; + } + + &.below { + top: calc(100% + 8px); + animation: slideDown 0.15s ease-out; + } +} + +@keyframes slideUp { + from { + opacity: 0; + transform: translateX(-50%) translateY(6px); + } + to { + opacity: 1; + transform: translateX(-50%) translateY(0); + } +} + +@keyframes slideDown { + from { + opacity: 0; + transform: translateX(-50%) translateY(-6px); + } + to { + opacity: 1; + transform: translateX(-50%) translateY(0); + } +} + +.style-buttons { + display: flex; + gap: 4px; +} + +.style-btn { + width: 32px; + height: 28px; + padding: 0; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 4px; + background: rgba(255, 255, 255, 0.03); + color: rgba(255, 255, 255, 0.7); + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; + + .style-text { + display: block; + } + + &.highlight-style .style-text { + background: linear-gradient(180deg, rgba(255, 255, 0, 0.4) 60%, transparent 60%); + } + + &.underline-style .style-text { + text-decoration: underline; + text-decoration-thickness: 2px; + } + + &.squiggly-style .style-text { + text-decoration: underline wavy; + } + + &.strikethrough-style .style-text { + text-decoration: line-through; + } + + &:hover { + border-color: rgba(255, 255, 255, 0.2); + background: rgba(255, 255, 255, 0.08); + color: #fff; + } + + &.selected { + border-color: #3b82f6; + background: rgba(59, 130, 246, 0.15); + color: #fff; + } +} + +.color-buttons { + display: flex; + gap: 6px; + justify-content: center; +} + +.color-btn { + width: 22px; + height: 22px; + padding: 0; + border: 2px solid transparent; + border-radius: 50%; + background: var(--color); + cursor: pointer; + transition: all 0.15s ease; + + &:hover { + transform: scale(1.1); + } + + &.selected { + border-color: #fff; + box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5); + } +} + diff --git a/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.ts new file mode 100644 index 000000000..213917bf2 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/shared/selection-popup.component.ts @@ -0,0 +1,147 @@ +import {Component, EventEmitter, Input, Output} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {ReaderIconComponent} from './icon.component'; + +export type AnnotationStyle = 'highlight' | 'underline' | 'strikethrough' | 'squiggly'; + +export interface TextSelectionAction { + type: 'select' | 'annotate' | 'delete' | 'dismiss' | 'preview' | 'search' | 'note'; + color?: string; + style?: AnnotationStyle; + annotationId?: number; + searchText?: string; +} + +@Component({ + selector: 'app-text-selection-popup', + standalone: true, + imports: [CommonModule, ReaderIconComponent], + templateUrl: './selection-popup.component.html', + styleUrls: ['./selection-popup.component.scss'] +}) +export class TextSelectionPopupComponent { + @Input() set visible(value: boolean) { + this._visible = value; + if (value) { + this.showAnnotationOptions = false; + this.hasPreview = false; + } + } + get visible(): boolean { + return this._visible; + } + private _visible = false; + + @Input() position = {x: 0, y: 0}; + @Input() showBelow = false; + @Input() overlappingAnnotationId: number | null = null; + @Input() selectedText = ''; + @Output() action = new EventEmitter(); + + showAnnotationOptions = false; + selectedColor = '#FFFF00'; + selectedStyle: AnnotationStyle = 'highlight'; + private hasPreview = false; + + highlightColors = [ + {value: '#FFFF00', label: 'Yellow'}, + {value: '#90EE90', label: 'Green'}, + {value: '#87CEEB', label: 'Blue'}, + {value: '#FFB6C1', label: 'Pink'}, + {value: '#FFD580', label: 'Orange'} + ]; + + lineColors = [ + {value: '#B8860B', label: 'Dark Gold'}, + {value: '#228B22', label: 'Forest Green'}, + {value: '#1E90FF', label: 'Dodger Blue'}, + {value: '#DC143C', label: 'Crimson'}, + {value: '#FF8C00', label: 'Dark Orange'} + ]; + + get colors() { + return this.selectedStyle === 'highlight' ? this.highlightColors : this.lineColors; + } + + styles: { value: AnnotationStyle; label: string; icon: string }[] = [ + {value: 'highlight', label: 'Highlight', icon: 'H'}, + {value: 'underline', label: 'Underline', icon: 'U'}, + {value: 'squiggly', label: 'Squiggly', icon: '~'}, + {value: 'strikethrough', label: 'Strikethrough', icon: 'S'} + ]; + + onSelect(): void { + this.action.emit({type: 'select'}); + this.showAnnotationOptions = false; + this.hasPreview = false; + } + + toggleAnnotationOptions(): void { + this.showAnnotationOptions = !this.showAnnotationOptions; + if (this.showAnnotationOptions) { + this.emitPreview(); + } + } + + selectColor(color: string): void { + this.selectedColor = color; + this.emitPreview(); + } + + selectStyle(style: AnnotationStyle): void { + const wasHighlight = this.selectedStyle === 'highlight'; + const isHighlight = style === 'highlight'; + + this.selectedStyle = style; + + if (wasHighlight !== isHighlight) { + this.selectedColor = isHighlight ? this.highlightColors[0].value : this.lineColors[0].value; + } + this.emitPreview(); + } + + private emitPreview(): void { + this.hasPreview = true; + this.action.emit({ + type: 'preview', + color: this.selectedColor, + style: this.selectedStyle + }); + } + + onDelete(): void { + if (this.overlappingAnnotationId) { + this.action.emit({type: 'delete', annotationId: this.overlappingAnnotationId}); + } + } + + onSearch(): void { + this.action.emit({type: 'search', searchText: this.selectedText}); + this.showAnnotationOptions = false; + this.hasPreview = false; + } + + onNote(): void { + this.action.emit({type: 'note'}); + this.showAnnotationOptions = false; + this.hasPreview = false; + } + + onDismiss(event: MouseEvent): void { + event.stopPropagation(); + event.preventDefault(); + + if (this.hasPreview) { + this.action.emit({ + type: 'annotate', + color: this.selectedColor, + style: this.selectedStyle + }); + } else { + this.action.emit({type: 'dismiss'}); + } + + this.showAnnotationOptions = false; + this.hasPreview = false; + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/utils/reader-header-footer-visibility.util.ts b/booklore-ui/src/app/features/readers/ebook-reader/shared/visibility.util.ts similarity index 96% rename from booklore-ui/src/app/features/readers/ebook-reader/utils/reader-header-footer-visibility.util.ts rename to booklore-ui/src/app/features/readers/ebook-reader/shared/visibility.util.ts index 6680a5798..040d3f126 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/utils/reader-header-footer-visibility.util.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/shared/visibility.util.ts @@ -8,8 +8,8 @@ export class ReaderHeaderFooterVisibilityManager { private mouseY = 0; private readonly HEADER_HEIGHT = 20; - private readonly FOOTER_HEIGHT = 20; - private readonly TRIGGER_ZONE = 20; + private readonly FOOTER_HEIGHT = 40; + private readonly TRIGGER_ZONE = 40; private headerVisible = false; private footerVisible = false; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/state/progress.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/state/progress.service.ts new file mode 100644 index 000000000..e9eb83a61 --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/state/progress.service.ts @@ -0,0 +1,169 @@ +import {inject, Injectable} from '@angular/core'; +import {Subject} from 'rxjs'; +import {BookPatchService} from '../../../book/service/book-patch.service'; +import {ReadingSessionService} from '../../../../shared/service/reading-session.service'; +import {PageInfo, ThemeInfo} from '../core/view-manager.service'; +import {ReaderViewManagerService} from '../core/view-manager.service'; +import {ReaderStateService} from './reader-state.service'; +import {ReaderAnnotationHttpService} from '../features/annotations/annotation.service'; +import {ReaderBookmarkService} from '../features/bookmarks/bookmark.service'; +import {BookType} from '../../../book/model/book.model'; + +export interface ProgressState { + cfi: string | null; + href: string | null; + chapterName: string | null; + chapterHref: string | null; + fraction: number; + pageInfo: PageInfo | undefined; + progressData: any; +} + +@Injectable() +export class ReaderProgressService { + private bookPatchService = inject(BookPatchService); + private readingSessionService = inject(ReadingSessionService); + private viewManager = inject(ReaderViewManagerService); + private stateService = inject(ReaderStateService); + private annotationService = inject(ReaderAnnotationHttpService); + private bookmarkService = inject(ReaderBookmarkService); + + private bookId!: number; + private bookType!: BookType; + private hasStartedSession = false; + + private _currentCfi: string | null = null; + private _currentChapterName: string | null = null; + private _currentChapterHref: string | null = null; + private _currentPageInfo: PageInfo | undefined; + private _currentProgressData: any = null; + + private progressSubject = new Subject(); + public progress$ = this.progressSubject.asObservable(); + + get currentCfi(): string | null { + return this._currentCfi; + } + + get currentChapterName(): string | null { + return this._currentChapterName; + } + + get currentChapterHref(): string | null { + return this._currentChapterHref; + } + + get currentProgressData(): any { + return this._currentProgressData; + } + + get currentPageInfo(): PageInfo | undefined { + return this._currentPageInfo; + } + + initialize(bookId: number, bookType: BookType): void { + this.bookId = bookId; + this.bookType = bookType; + this.hasStartedSession = false; + } + + 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.bookId, this.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; + this.annotationService.updateCurrentChapter(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`); + + this._currentPageInfo = { + percentCompleted, + sectionTimeText: parts.join(' ') + }; + } + + if (this.stateService.currentState.flow === 'paginated') { + this.updateHeadersAndFooters(); + } + + if (cfi) { + this._currentCfi = cfi; + this.bookmarkService.updateCurrentPosition(cfi, chapterLabel); + } + + this.progressSubject.next({ + cfi: this._currentCfi, + href, + chapterName: this._currentChapterName, + chapterHref: this._currentChapterHref, + fraction: detail?.fraction ?? 0, + pageInfo: this._currentPageInfo, + progressData: this._currentProgressData + }); + } + + updateHeadersAndFooters(): void { + const renderer = this.viewManager.getRenderer(); + if (!renderer) return; + + 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 + ); + } + + endSession(): void { + 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); + } + } + + reset(): void { + this._currentCfi = null; + this._currentChapterName = null; + this._currentChapterHref = null; + this._currentPageInfo = undefined; + this._currentProgressData = null; + this.hasStartedSession = false; + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-state.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/state/reader-state.service.ts similarity index 98% rename from booklore-ui/src/app/features/readers/ebook-reader/services/reader-state.service.ts rename to booklore-ui/src/app/features/readers/ebook-reader/state/reader-state.service.ts index ffa214140..67567c945 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-state.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/state/reader-state.service.ts @@ -1,10 +1,10 @@ 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 {Theme, themes} from './themes.constant'; import {BookService} from '../../../book/service/book.service'; import {UserService} from '../../../settings/user-management/user.service'; -import {EpubCustomFontService} from './epub-custom-font.service'; +import {EpubCustomFontService} from '../features/fonts/custom-font.service'; export interface ReaderState { lineHeight: number; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/services/reader-themes.ts b/booklore-ui/src/app/features/readers/ebook-reader/state/themes.constant.ts similarity index 100% rename from booklore-ui/src/app/features/readers/ebook-reader/services/reader-themes.ts rename to booklore-ui/src/app/features/readers/ebook-reader/state/themes.constant.ts diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts index 48dd56362..a9a5affc1 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts @@ -9,7 +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'; +import {themes} from '../../../readers/ebook-reader/state/themes.constant'; @Component({ selector: 'app-epub-reader-preferences-component', diff --git a/booklore-ui/src/app/shared/service/annotation.service.ts b/booklore-ui/src/app/shared/service/annotation.service.ts new file mode 100644 index 000000000..ea4542b71 --- /dev/null +++ b/booklore-ui/src/app/shared/service/annotation.service.ts @@ -0,0 +1,61 @@ +import {Injectable, inject} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {Observable} from 'rxjs'; +import {API_CONFIG} from '../../core/config/api-config'; + +export type AnnotationStyle = 'highlight' | 'underline' | 'strikethrough' | 'squiggly'; + +export interface Annotation { + id: number; + userId?: number; + bookId: number; + cfi: string; + text: string; + color: string; + style: AnnotationStyle; + note?: string; + chapterTitle?: string; + createdAt: string; + updatedAt?: string; +} + +export interface CreateAnnotationRequest { + bookId: number; + cfi: string; + text: string; + color?: string; + style?: AnnotationStyle; + note?: string; + chapterTitle?: string; +} + +export interface UpdateAnnotationRequest { + color?: string; + style?: AnnotationStyle; + note?: string; +} + +@Injectable({ + providedIn: 'root' +}) +export class AnnotationService { + + private readonly url = `${API_CONFIG.BASE_URL}/api/v1/annotations`; + private readonly http = inject(HttpClient); + + getAnnotationsForBook(bookId: number): Observable { + return this.http.get(`${this.url}/book/${bookId}`); + } + + createAnnotation(request: CreateAnnotationRequest): Observable { + return this.http.post(this.url, request); + } + + deleteAnnotation(annotationId: number): Observable { + return this.http.delete(`${this.url}/${annotationId}`); + } + + updateAnnotation(annotationId: number, request: UpdateAnnotationRequest): Observable { + return this.http.put(`${this.url}/${annotationId}`, request); + } +} diff --git a/booklore-ui/src/app/shared/service/book-note-v2.service.ts b/booklore-ui/src/app/shared/service/book-note-v2.service.ts new file mode 100644 index 000000000..dcf9af5cb --- /dev/null +++ b/booklore-ui/src/app/shared/service/book-note-v2.service.ts @@ -0,0 +1,57 @@ +import {Injectable, inject} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {Observable} from 'rxjs'; +import {API_CONFIG} from '../../core/config/api-config'; + +export interface BookNoteV2 { + id: number; + userId?: number; + bookId: number; + cfi: string; + selectedText?: string; + noteContent: string; + color?: string; + chapterTitle?: string; + createdAt: string; + updatedAt?: string; +} + +export interface CreateBookNoteV2Request { + bookId: number; + cfi: string; + selectedText?: string; + noteContent: string; + color?: string; + chapterTitle?: string; +} + +export interface UpdateBookNoteV2Request { + noteContent?: string; + color?: string; + chapterTitle?: string; +} + +@Injectable({ + providedIn: 'root' +}) +export class BookNoteV2Service { + + private readonly url = `${API_CONFIG.BASE_URL}/api/v2/book-notes`; + private readonly http = inject(HttpClient); + + getNotesForBook(bookId: number): Observable { + return this.http.get(`${this.url}/book/${bookId}`); + } + + createNote(request: CreateBookNoteV2Request): Observable { + return this.http.post(this.url, request); + } + + deleteNote(noteId: number): Observable { + return this.http.delete(`${this.url}/${noteId}`); + } + + updateNote(noteId: number, request: UpdateBookNoteV2Request): Observable { + return this.http.put(`${this.url}/${noteId}`, request); + } +}