Add support for annotations and book notes in the new ebook reader (#2313)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-17 22:36:00 -07:00
committed by GitHub
co-authored by acx10
parent d75e7e228a
commit e5b1d33bf7
79 changed files with 7481 additions and 1806 deletions
@@ -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<Annotation> 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<Void> deleteAnnotation(
@Parameter(description = "ID of the annotation to delete") @PathVariable Long annotationId) {
annotationService.deleteAnnotation(annotationId);
return ResponseEntity.noContent().build();
}
}
@@ -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<BookNoteV2> 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<Void> deleteNote(
@Parameter(description = "ID of the note to delete") @PathVariable Long noteId) {
bookNoteV2Service.deleteNote(noteId);
return ResponseEntity.noContent().build();
}
}
@@ -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);
}
@@ -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);
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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;
}
@@ -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<AnnotationEntity, Long> {
Optional<AnnotationEntity> 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<AnnotationEntity> 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);
}
@@ -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<BookNoteV2Entity, Long> {
Optional<BookNoteV2Entity> 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<BookNoteV2Entity> 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);
}
@@ -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<Annotation> 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);
}
}
@@ -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<BookNoteV2> 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);
}
}
@@ -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;
@@ -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;
@@ -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<BookNoteV2> expectedNotes = List.of(note1, note2);
when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(expectedNotes);
List<BookNoteV2> 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<BookNoteV2> 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<Void> 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<BookNoteV2> notes = List.of(createSampleNote(1L), createSampleNote(2L), createSampleNote(3L));
when(bookNoteV2Service.getNotesForBook(bookId)).thenReturn(notes);
List<BookNoteV2> 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();
}
}
@@ -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<BookNoteV2> 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<BookNoteV2> 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<BookNoteV2Entity> 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<BookNoteV2Entity> 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<BookNoteV2> 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());
}
}
@@ -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<ViewEvent>();
public events$ = this.eventSubject.asObservable();
createView(container: HTMLElement): void {
this.view = document.createElement('foliate-view');
this.view.style.width = '100%';
this.view.style.height = '100%';
this.view.style.display = 'block';
container.appendChild(this.view);
this.attachEventListeners();
initialize(view: any, callbacks: ViewCallbacks): void {
this.view = view;
this.viewCallbacks = callbacks;
this.attachViewEventListeners();
this.attachKeyboardHandler();
}
loadEpub(epubPath: string): Observable<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return timer(100).pipe(
switchMap(() => from(fetch(epubPath))),
switchMap(response => {
if (!response.ok) {
throw new Error(`EPUB not found: ${response.status}`);
}
return from(response.blob());
}),
switchMap(blob => {
const file = new File([blob], epubPath.split('/').pop() || 'book.epub', {
type: 'application/epub+zip'
});
return from(this.view.open(file) as Promise<void>);
}),
map(() => undefined),
catchError(err => throwError(() => err))
);
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<Document>();
}
goTo(target?: string | number | null): Observable<void> {
const resolvedTarget = target ?? 0;
if (!this.view) {
return of(undefined);
}
return defer(() =>
from(this.view.goTo(resolvedTarget) as Promise<void>)
).pipe(
map(() => undefined)
);
emit(event: ViewEvent): void {
this.eventSubject.next(event);
}
goToSection(index: number): Observable<void> {
return this.goTo(index);
}
private attachViewEventListeners(): void {
if (!this.view) return;
goToFraction(fraction: number): Observable<void> {
if (!this.view) {
return of(undefined);
}
return defer(() => from(this.view.goToFraction(fraction) as Promise<void>)).pipe(
map(() => undefined)
);
}
prev(): void {
this.view?.prev();
}
next(): void {
this.view?.next();
}
getRenderer(): any {
return this.view?.renderer;
}
updateHeadersAndFooters(chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void {
const renderer = this.getRenderer();
ReaderHeaderFooterUtil.updateHeadersAndFooters(renderer, chapterName, pageInfo, theme);
}
getChapters(): TocItem[] {
if (!this.view?.book?.toc) return [];
const mapToc = (items: any[]): TocItem[] =>
items.map(item => ({
label: item.label,
href: item.href,
subitems: item.subitems?.length ? mapToc(item.subitems) : undefined
}));
return mapToc(this.view.book.toc);
}
getSectionFractions(): number[] {
if (!this.view?.getSectionFractions) return [];
return this.view.getSectionFractions();
}
getMetadata(): Observable<BookMetadata> {
if (!this.view?.book?.metadata) {
return of({});
}
const {metadata} = this.view.book;
return this.getCoverUrl().pipe(
map(coverUrl => ({
title: metadata.title,
authors: metadata.authors,
language: metadata.language,
publisher: metadata.publisher,
description: metadata.description,
identifier: metadata.identifier,
coverUrl,
...metadata
}))
);
}
getCover(): Observable<Blob | null> {
if (!this.view?.book?.getCover) {
return of(null);
}
return defer(() => {
const coverPromise = this.view.book.getCover();
return coverPromise ? from(coverPromise as Promise<Blob | null>) : of(null);
});
}
getCoverUrl(): Observable<string | null> {
return this.getCover().pipe(
map(blob => blob ? URL.createObjectURL(blob) : null)
);
}
private attachEventListeners(): void {
this.view.addEventListener('load', (e: any) => {
this.eventSubject.next({type: 'load', detail: e.detail});
if (e.detail?.doc) {
@@ -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'});
@@ -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);
}
`;
}
@@ -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<ViewEvent> {
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<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return timer(100).pipe(
switchMap(() => from(fetch(epubPath))),
switchMap(response => {
if (!response.ok) {
throw new Error(`EPUB not found: ${response.status}`);
}
return from(response.blob());
}),
switchMap(blob => {
const file = new File([blob], epubPath.split('/').pop() || 'book.epub', {
type: 'application/epub+zip'
});
return from(this.view.open(file) as Promise<void>);
}),
map(() => undefined),
catchError(err => throwError(() => err))
);
}
destroy(): void {
this.eventService.destroy();
this.annotationService.clearAnnotations();
this.view?.remove();
this.view = null;
}
goTo(target?: string | number | null): Observable<void> {
const resolvedTarget = target ?? 0;
if (!this.view) {
return of(undefined);
}
return defer(() =>
from(this.view.goTo(resolvedTarget) as Promise<void>)
).pipe(
map(() => undefined)
);
}
goToSection(index: number): Observable<void> {
return this.goTo(index);
}
goToFraction(fraction: number): Observable<void> {
if (!this.view) {
return of(undefined);
}
return defer(() => from(this.view.goToFraction(fraction) as Promise<void>)).pipe(
map(() => undefined)
);
}
prev(): void {
this.view?.prev();
}
next(): void {
this.view?.next();
}
getRenderer(): any {
return this.view?.renderer;
}
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<void> {
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<BookMetadata> {
if (!this.view?.book?.metadata) {
return of({});
}
const {metadata} = this.view.book;
return this.getCoverUrl().pipe(
map(coverUrl => ({
title: metadata.title,
authors: metadata.authors,
language: metadata.language,
publisher: metadata.publisher,
description: metadata.description,
identifier: metadata.identifier,
coverUrl,
...metadata
}))
);
}
getCover(): Observable<Blob | null> {
if (!this.view?.book?.getCover) {
return of(null);
}
return defer(() => {
const coverPromise = this.view.book.getCover();
return coverPromise ? from(coverPromise as Promise<Blob | null>) : of(null);
});
}
getCoverUrl(): Observable<string | null> {
return this.getCover().pipe(
map(blob => blob ? URL.createObjectURL(blob) : null)
);
}
async* search(opts: { query: string; matchCase?: boolean; matchWholeWords?: boolean }): AsyncGenerator<any> {
if (!this.view?.search) return;
yield* this.view.search(opts);
}
clearSearch(): void {
this.view?.clearSearch?.();
}
}
@@ -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;
}
@@ -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;
@@ -0,0 +1,51 @@
<div class="dialog-overlay" (click)="onOverlayClick($event)">
<div class="dialog">
<div class="dialog-header">
<h2>{{ isEditing ? 'Edit Note' : 'Add Note' }}</h2>
<button class="close-btn" (click)="onCancel()">
<app-reader-icon name="close" [size]="18"></app-reader-icon>
</button>
</div>
<div class="dialog-body">
@if (data?.selectedText) {
<div class="selected-text-section">
<span class="section-label">Selected Text</span>
<p class="selected-text">"{{ data?.selectedText }}"</p>
</div>
}
<div class="note-section">
<label class="section-label" for="noteContent">Your Note</label>
<textarea
id="noteContent"
class="note-input"
[(ngModel)]="noteContent"
placeholder="Write your note here..."
rows="6"
autofocus
></textarea>
</div>
<div class="color-section">
<span class="section-label">Note Color</span>
<div class="color-buttons">
@for (color of noteColors; track color.value) {
<button
class="color-btn"
[style.--color]="color.value"
[class.selected]="selectedColor === color.value"
[title]="color.label"
(click)="selectColor(color.value)">
</button>
}
</div>
</div>
</div>
<div class="dialog-footer">
<button class="btn btn-secondary" (click)="onCancel()">Cancel</button>
<button class="btn btn-primary" (click)="onSave()" [disabled]="!noteContent.trim()">{{ isEditing ? 'Update Note' : 'Save Note' }}</button>
</div>
</div>
</div>
@@ -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;
}
}
@@ -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<NoteDialogResult>();
@Output() cancel = new EventEmitter<void>();
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();
}
}
}
@@ -58,6 +58,22 @@
</label>
}
</div>
<div class="section-header">Annotation Highlighter</div>
<div class="annotation-colors">
@for (color of annotationColors; track color.name) {
<button
class="color-picker-btn"
[class.active]="selectedAnnotationColor === color.value"
[style.background-color]="color.value"
[attr.aria-label]="color.label"
(click)="setAnnotationColor(color.value)">
@if (selectedAnnotationColor === color.value) {
<span class="check-icon">✓</span>
}
</button>
}
</div>
</div>
}
@@ -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;
}
}
@@ -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;
}
}
@@ -11,41 +11,11 @@
</div>
}
<app-reader-header
[bookTitle]="book?.metadata?.title!"
[currentTheme]="stateService.currentState.theme"
[isDark]="stateService.currentState.isDark"
[fontSize]="stateService.currentState.fontSize"
[lineHeight]="stateService.currentState.lineHeight"
[forceVisible]="forceHeaderVisible"
[flow]="stateService.currentState.flow"
(setFlow)="onSetFlow($event)"
(showChapters)="showChapters = true"
(showControls)="showControls = true"
(showMetadata)="showMetadata = true"
(createBookmark)="onCreateBookmark()"
(close)="location.back()"
(toggleDarkMode)="onToggleDarkMode()"
(increaseFontSize)="onIncreaseFontSize()"
(decreaseFontSize)="onDecreaseFontSize()"
(increaseLineHeight)="onIncreaseLineHeight()"
(decreaseLineHeight)="onDecreaseLineHeight()"
></app-reader-header>
<app-reader-header></app-reader-header>
<div class="reader-content" style="position: relative;">
@if (isCurrentCfiBookmarked) {
<div
style="
position: absolute;
top: 0;
left: 12px;
z-index: 10;
width: 48px;
height: 64px;
background: none;
pointer-events: none;
">
<div class="bookmark-indicator">
<svg width="48" height="64" viewBox="0 0 48 64">
<polygon points="0,0 48,0 48,64 24,48 0,64" fill="red"/>
</svg>
@@ -61,21 +31,16 @@
(progressChange)="onProgressChange($event)">
</app-reader-navbar>
@if (showChapters) {
<app-reader-sidebar
[bookId]="book?.id ?? null"
[coverUpdatedOn]="coverUpdatedOn"
[bookTitle]="book?.metadata?.title ?? ''"
[bookAuthors]="(book?.metadata?.authors ?? []).join(', ')"
[chapters]="chapters"
[bookmarks]="bookmarks"
[currentChapterHref]="currentChapterHref"
(close)="showChapters = false"
(chapterClick)="onChapterClick($event)"
(bookmarkClick)="onBookmarkClick($event)"
(deleteBookmark)="onDeleteBookmark($event)"
(coverClick)="showMetadata = true"
></app-reader-sidebar>
<app-reader-sidebar></app-reader-sidebar>
<app-reader-left-sidebar></app-reader-left-sidebar>
@if (showQuickSettings) {
<app-reader-quick-settings
[stateService]="stateService"
[bookId]="bookId"
(close)="showQuickSettings = false"
(openFullSettings)="showControls = true">
</app-reader-quick-settings>
}
@if (showControls) {
@@ -93,4 +58,21 @@
(close)="showMetadata = false"
></app-reader-book-metadata-dialog>
}
<app-text-selection-popup
[visible]="showSelectionPopup"
[position]="popupPosition"
[showBelow]="showPopupBelow"
[overlappingAnnotationId]="overlappingAnnotationId"
[selectedText]="selectedText"
(action)="handleSelectionAction($event)"
></app-text-selection-popup>
@if (showNoteDialog) {
<app-reader-note-dialog
[data]="noteDialogData"
(save)="onNoteSave($event)"
(cancel)="onNoteCancel()"
></app-reader-note-dialog>
}
</div>
@@ -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;
@@ -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();
}
}
@@ -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<string, { color: string; style: AnnotationStyle }>();
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<void> {
if (!view) return of(undefined);
this.annotationStyles.delete(cfi);
return defer(() => from(view.deleteAnnotation({value: cfi}) as Promise<void>));
}
showAnnotation(view: any, cfi: string): Observable<void> {
if (!view) return of(undefined);
return defer(() => from(view.showAnnotation({value: cfi}) as Promise<void>));
}
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();
}
}
@@ -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<Annotation | null> {
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<Annotation[]> {
return this.annotationService.getAnnotationsForBook(bookId).pipe(
catchError(() => {
return of([]);
})
);
}
deleteAnnotation(annotationId: number): Observable<boolean> {
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<Annotation | null> {
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;
}
}
@@ -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<boolean> {
const cfi = this.currentCFI;
if (!cfi) {
console.error('Could not get current CFI - please navigate to a page first');
return of(false);
}
@@ -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';
@@ -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<void>();
private dialogStateSubject = new BehaviorSubject<NoteDialogState>({
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>): 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
});
}
}
@@ -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<void>();
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<SelectionState>();
public state$ = this.stateSubject.asObservable();
private annotationsChangedSubject = new Subject<Annotation[]>();
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>): 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();
}
}
@@ -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';
@@ -1,11 +1,6 @@
<div
class="reader-navbar"
[style.color]="'#ffffff'"
[style.background]="'#1a1a1a'"
[class.visible]="navbarVisible">
<button class="icon-btn" title="Previous">
<i class="pi pi-caret-left" aria-label="Previous"></i>
<div class="reader-navbar" [class.visible]="navbarVisible">
<button class="icon-btn" title="Previous Section" [disabled]="!canGoPrevious" (click)="onPreviousSection()">
<app-reader-icon name="chevron-left"></app-reader-icon>
</button>
<div class="progress-section">
@@ -23,20 +18,20 @@
(input)="onProgressChange($event)"
title="Progress"/>
<div class="progress-ticks">
@for (frac of sectionFractions; track frac) {
@for (frac of displaySectionFractions; track frac) {
<span class="progress-tick" [style.left.%]="frac * 100"></span>
}
</div>
</div>
</div>
<button class="icon-btn" title="Next">
<i class="pi pi-caret-right" aria-label="Next"></i>
<button class="icon-btn" title="Next Section" [disabled]="!canGoNext" (click)="onNextSection()">
<app-reader-icon name="chevron-right"></app-reader-icon>
</button>
</div>
@if (showLocationPopover) {
<div class="location-popover" [style.color]="'#ffffff'" [style.background]="'#1a1a1a'" (mousedown)="$event.preventDefault()">
<div class="location-popover" (mousedown)="$event.preventDefault()">
<div class="popover-content">
<div class="time-info">
<div class="time-section">
@@ -72,19 +67,19 @@
<div class="section-navigation">
<button class="nav-btn" title="First Section" (click)="onFirstSection()">
<i class="pi pi-step-backward"></i>
<app-reader-icon name="chevron-first" [size]="16"></app-reader-icon>
</button>
<button class="nav-btn" title="Previous Section" (click)="onPreviousSection()">
<i class="pi pi-caret-left"></i>
<app-reader-icon name="chevron-left" [size]="16"></app-reader-icon>
</button>
<button class="nav-btn" title="Jump To…">
<i class="pi pi-ellipsis-v"></i>
<button class="nav-btn" title="Jump To...">
<app-reader-icon name="dots-vertical" [size]="16"></app-reader-icon>
</button>
<button class="nav-btn" title="Next Section" (click)="onNextSection()">
<i class="pi pi-caret-right"></i>
<app-reader-icon name="chevron-right" [size]="16"></app-reader-icon>
</button>
<button class="nav-btn" title="Last Section" (click)="onLastSection()">
<i class="pi pi-step-forward"></i>
<app-reader-icon name="chevron-last" [size]="16"></app-reader-icon>
</button>
</div>
</div>
@@ -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);
}
}
}
}
@@ -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<number>();
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;
@@ -0,0 +1,18 @@
<div class="reader-header" [class.visible]="isVisible" [style.background]="currentTheme.bg" [style.color]="currentTheme.fg">
<button class="icon-btn" (click)="onShowChapters()" title="Chapters">
<app-reader-icon name="menu" [size]="20"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onCreateBookmark()" title="Create Bookmark">
<app-reader-icon name="bookmark"></app-reader-icon>
</button>
<span class="chapter-title">{{ bookTitle }}</span>
<button class="icon-btn" (click)="onOpenSearch()" title="Search">
<app-reader-icon name="search"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onShowControls()" title="Settings">
<app-reader-icon name="settings"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onClose(); $event.stopPropagation()" title="Close Reader">
<app-reader-icon name="close"></app-reader-icon>
</button>
</div>
@@ -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<void>();
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();
}
}
@@ -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<void>();
private bookId!: number;
private bookTitle = '';
private _forceVisible = new BehaviorSubject<boolean>(false);
forceVisible$ = this._forceVisible.asObservable();
private _showControls = new Subject<void>();
private _showMetadata = new Subject<void>();
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>): 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 = '';
}
}
@@ -0,0 +1,53 @@
<div class="dialog-overlay" (click)="onOverlayClick($event)">
<div class="dialog" (click)="$event.stopPropagation()">
<div class="dialog-header">
<h3 class="dialog-title">Quick Settings</h3>
<button class="close-btn" (click)="close.emit()">✕</button>
</div>
<div class="dialog-body">
<!-- Dark Mode -->
<div class="control">
<label>Dark Mode</label>
<div class="control-right">
<span class="mode-icon sun" [class.active]="!isDarkMode">☀️</span>
<button class="switch" [class.active]="isDarkMode" (click)="toggleDarkMode()">
<span class="slider"></span>
</button>
<span class="mode-icon moon" [class.active]="isDarkMode">🌙</span>
</div>
</div>
<!-- Font Size -->
<div class="control">
<label>Font Size</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseFontSize()">−</button>
<span>{{ state.fontSize }}%</span>
<button (click)="increaseFontSize()">+</button>
</div>
</div>
</div>
<!-- Line Spacing -->
<div class="control">
<label>Line Spacing</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseLineHeight()">−</button>
<span>{{ state.lineHeight | number:'1.1-1' }}</span>
<button (click)="increaseLineHeight()">+</button>
</div>
</div>
</div>
</div>
<div class="dialog-footer">
<button class="more-settings-btn" (click)="onOpenFullSettings()">
<app-reader-icon name="settings" [size]="16"></app-reader-icon>
<span>More Settings</span>
</button>
</div>
</div>
</div>
@@ -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);
}
}
@@ -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<void>();
@Output() openFullSettings = new EventEmitter<void>();
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();
}
}
}
@@ -0,0 +1,171 @@
@if (isOpen) {
<div class="sidebar-overlay" (click)="onOverlayClick()" [class.closing]="closing">
<aside class="sidebar" (click)="$event.stopPropagation()" [class.closing]="closing">
<!-- Header -->
<header class="sidebar-header">
<h2 class="sidebar-title">
@if (activeTab === 'search') {
Search
} @else {
Notes
}
</h2>
</header>
<!-- Tab navigation -->
<nav class="tabs">
<button
class="tab"
[class.active]="activeTab === 'search'"
(click)="setActiveTab('search')">
<app-reader-icon name="search" class="tab-icon"></app-reader-icon>
<span>Search</span>
@if (searchState.results.length > 0) {
<span class="badge">{{ searchState.results.length }}</span>
}
</button>
<button
class="tab"
[class.active]="activeTab === 'notes'"
(click)="setActiveTab('notes')">
<app-reader-icon name="note" class="tab-icon"></app-reader-icon>
<span>Notes</span>
@if (notes.length > 0) {
<span class="badge">{{ notes.length }}</span>
}
</button>
</nav>
<!-- Tab content -->
<div class="content">
@switch (activeTab) {
@case ('search') {
<div class="search-container">
<div class="search-input-wrapper">
<app-reader-icon name="search" class="search-icon" [size]="16"></app-reader-icon>
<input
type="text"
class="search-input"
placeholder="Search in book..."
[(ngModel)]="searchQuery"
(ngModelChange)="onSearchInput($event)"
autofocus
/>
@if (searchQuery) {
<button class="clear-btn" (click)="clearSearch()" aria-label="Clear search">
<app-reader-icon name="close" [size]="14"></app-reader-icon>
</button>
}
</div>
@if (searchState.isSearching) {
<div class="search-progress">
<div class="progress-bar">
<div class="progress-fill" [style.width.%]="searchState.progress * 100"></div>
</div>
<span class="progress-text">Searching... {{ (searchState.progress * 100) | number:'1.0-0' }}%</span>
</div>
}
@if (searchState.results.length > 0) {
<div class="search-results-header">
<span>{{ searchState.results.length }} result{{ searchState.results.length === 1 ? '' : 's' }} found</span>
</div>
<ul class="item-list search-results">
@for (result of searchState.results; track result.cfi) {
<li class="list-item search-result-item" (click)="onSearchResultClick(result.cfi)">
<div class="item-content">
<span class="search-excerpt">
<span class="excerpt-context">{{ result.excerpt.pre }}</span>
<mark class="excerpt-match">{{ result.excerpt.match }}</mark>
<span class="excerpt-context">{{ result.excerpt.post }}</span>
</span>
@if (result.sectionLabel) {
<span class="item-chapter">{{ result.sectionLabel }}</span>
}
</div>
</li>
}
</ul>
} @else if (!searchState.isSearching && searchQuery) {
<div class="empty-state">
<app-reader-icon name="search" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>No results found</p>
<span class="empty-hint">Try different keywords</span>
</div>
} @else if (!searchQuery) {
<div class="empty-state">
<app-reader-icon name="search" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>Search this book</p>
<span class="empty-hint">Enter text to find in the book</span>
</div>
}
</div>
}
@case ('notes') {
<div class="notes-container">
@if (notes.length > 0) {
<div class="notes-search-wrapper">
<app-reader-icon name="search" class="search-icon" [size]="16"></app-reader-icon>
<input
type="text"
class="search-input"
placeholder="Search notes..."
[(ngModel)]="notesSearchQuery"
(ngModelChange)="onNotesSearchInput($event)"
/>
@if (notesSearchQuery) {
<button class="clear-btn" (click)="clearNotesSearch()" aria-label="Clear search">
<app-reader-icon name="close" [size]="14"></app-reader-icon>
</button>
}
</div>
}
@if (filteredNotes.length > 0) {
<ul class="item-list">
@for (note of filteredNotes; track note.id) {
<li class="list-item note-item" (click)="onNoteClick(note.cfi)">
<div class="note-bar" [style.background-color]="note.color"></div>
<div class="item-content">
<span class="note-text">{{ note.noteContent }}</span>
@if (note.selectedText) {
<span class="note-selected-text">"{{ note.selectedText }}"</span>
}
@if (note.chapterTitle) {
<span class="item-chapter">{{ note.chapterTitle }}</span>
}
<span class="item-meta">{{ note.createdAt | date: 'MMM d, y' }}</span>
</div>
<div class="action-buttons">
<button class="edit-btn" (click)="onEditNote($event, note)" aria-label="Edit note">
<app-reader-icon name="edit" [size]="16"></app-reader-icon>
</button>
<button class="delete-btn" (click)="onDeleteNote($event, note.id)" aria-label="Delete note">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</div>
</li>
}
</ul>
} @else if (notes.length > 0 && notesSearchQuery) {
<div class="empty-state">
<app-reader-icon name="search" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>No matching notes</p>
<span class="empty-hint">Try different search terms</span>
</div>
} @else {
<div class="empty-state">
<app-reader-icon name="note" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>No notes yet</p>
<span class="empty-hint">Select text and tap the note icon to add a note</span>
</div>
}
</div>
}
}
</div>
</aside>
</div>
}
@@ -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%); }
}
@@ -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<void>();
isOpen = false;
closing = false;
activeTab: LeftSidebarTab = 'search';
notes: BookNoteV2[] = [];
notesSearchQuery = '';
searchState: SearchState = { query: '', results: [], isSearching: false, progress: 0 };
searchQuery = '';
private searchInput$ = new Subject<string>();
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();
}
}
@@ -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<void>();
private bookId!: number;
private _isOpen = new BehaviorSubject<boolean>(false);
private _activeTab = new BehaviorSubject<LeftSidebarTab>('search');
private _notes = new BehaviorSubject<BookNoteV2[]>([]);
private _notesSearchQuery = new BehaviorSubject<string>('');
private _searchState = new BehaviorSubject<SearchState>({
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<BookNoteV2>();
editNote$ = this._editNote.asObservable();
initialize(bookId: number, destroy$: Subject<void>): 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<void> {
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();
}
}
@@ -0,0 +1,150 @@
@if (isOpen) {
<div class="sidebar-overlay" (click)="onOverlayClick()" [class.closing]="closing">
<aside class="sidebar" (click)="$event.stopPropagation()" [class.closing]="closing">
<!-- Header with book info -->
<header class="sidebar-header">
@if (bookInfo.coverUrl) {
<img
[src]="bookInfo.coverUrl"
alt="Book cover"
class="book-cover"
(click)="onCoverClick()"
role="button"
tabindex="0"
(keydown.enter)="onCoverClick()"
/>
}
<div class="book-meta">
<h2 class="book-title">{{ bookInfo.title }}</h2>
@if (bookInfo.authors) {
<p class="book-authors">{{ bookInfo.authors }}</p>
}
</div>
</header>
<!-- Tab navigation -->
<nav class="tabs">
<button
class="tab"
[class.active]="activeTab === 'chapters'"
(click)="setActiveTab('chapters')">
<app-reader-icon name="book" class="tab-icon"></app-reader-icon>
<span>Contents</span>
</button>
<button
class="tab"
[class.active]="activeTab === 'bookmarks'"
(click)="setActiveTab('bookmarks')">
<app-reader-icon name="bookmark" class="tab-icon"></app-reader-icon>
<span>Bookmarks</span>
@if (bookmarks.length > 0) {
<span class="badge">{{ bookmarks.length }}</span>
}
</button>
<button
class="tab"
[class.active]="activeTab === 'highlights'"
(click)="setActiveTab('highlights')">
<app-reader-icon name="edit" class="tab-icon"></app-reader-icon>
<span>Highlights</span>
@if (annotations.length > 0) {
<span class="badge">{{ annotations.length }}</span>
}
</button>
</nav>
<!-- Tab content -->
<div class="content">
@switch (activeTab) {
@case ('chapters') {
<ul class="chapter-list" role="tree">
@for (chapter of chapters; track chapter.href) {
<ng-container *ngTemplateOutlet="chapterItem; context: { $implicit: chapter, depth: 0 }"/>
}
</ul>
<ng-template #chapterItem let-chapter let-depth="depth">
<li role="treeitem">
<button
class="chapter-row"
[class.active]="isChapterActive(chapter.href)"
[class.expandable]="chapter.subitems?.length"
[style.--depth]="depth"
(click)="onChapterClick(chapter)">
<span class="chapter-label">{{ chapter.label }}</span>
@if (chapter.subitems?.length) {
<app-reader-icon
name="chevron-right"
class="expand-icon"
[class.expanded]="isChapterExpanded(chapter.href)"
[size]="16">
</app-reader-icon>
}
</button>
@if (chapter.subitems?.length && isChapterExpanded(chapter.href)) {
<ul class="subchapter-list" role="group">
@for (sub of chapter.subitems; track sub.href) {
<ng-container *ngTemplateOutlet="chapterItem; context: { $implicit: sub, depth: depth + 1 }"/>
}
</ul>
}
</li>
</ng-template>
}
@case ('bookmarks') {
@if (bookmarks.length > 0) {
<ul class="item-list">
@for (bookmark of bookmarks; track bookmark.id) {
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi)">
<div class="item-content">
<span class="item-title">{{ bookmark.title }}</span>
<span class="item-meta">{{ bookmark.createdAt | date: 'MMM d, y' }}</span>
</div>
<button class="delete-btn" (click)="onDeleteBookmark($event, bookmark.id)" aria-label="Delete bookmark">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</li>
}
</ul>
} @else {
<div class="empty-state">
<app-reader-icon name="bookmark" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>No bookmarks yet</p>
<span class="empty-hint">Tap the bookmark icon to save your place</span>
</div>
}
}
@case ('highlights') {
@if (annotations.length > 0) {
<ul class="item-list">
@for (annotation of annotations; track annotation.id) {
<li class="list-item highlight-item" (click)="onAnnotationClick(annotation.cfi)">
<div class="highlight-bar" [style.background-color]="annotation.color"></div>
<div class="item-content">
<span class="highlight-text">"{{ annotation.text }}"</span>
@if (annotation.chapterTitle) {
<span class="item-chapter">{{ annotation.chapterTitle }}</span>
}
<span class="item-meta">{{ annotation.createdAt | date: 'MMM d, y' }}</span>
</div>
<button class="delete-btn" (click)="onDeleteAnnotation($event, annotation.id)" aria-label="Delete highlight">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</li>
}
</ul>
} @else {
<div class="empty-state">
<app-reader-icon name="edit" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>No highlights yet</p>
<span class="empty-hint">Select text to create a highlight</span>
</div>
}
}
}
</div>
</aside>
</div>
}
@@ -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%); }
}
@@ -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<void>();
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();
}
}
@@ -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<void>();
private bookId!: number;
private selectionService: ReaderSelectionService | null = null;
private _isOpen = new BehaviorSubject<boolean>(false);
private _activeTab = new BehaviorSubject<SidebarTab>('chapters');
private _bookInfo = new BehaviorSubject<SidebarBookInfo>({
id: null,
title: '',
authors: '',
coverUrl: null
});
private _chapters = new BehaviorSubject<TocItem[]>([]);
private _bookmarks = new BehaviorSubject<BookMark[]>([]);
private _annotations = new BehaviorSubject<Annotation[]>([]);
private _expandedChapters = new Set<string>();
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<void>();
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>): 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();
}
}
@@ -1,19 +0,0 @@
<div
class="reader-header"
[style.color]="currentTheme?.fg ?? ''"
[style.background]="currentTheme?.bg ?? ''"
[class.visible]="headerVisible">
<button class="icon-btn" (click)="showChapters.emit()" title="Chapters">
<i class="pi pi-bars" aria-label="Chapters"></i>
</button>
<button class="icon-btn" (click)="createBookmark.emit()" title="Create Bookmark">
<i class="pi pi-bookmark" aria-label="Create Bookmark"></i>
</button>
<span class="chapter-title">{{ bookTitle || '' }}</span>
<button class="icon-btn" (click)="showControls.emit()" title="Settings">
<i class="pi pi-cog" aria-label="Settings"></i>
</button>
<button class="icon-btn" (click)="close.emit(); $event.stopPropagation()" title="Close Reader">
<i class="pi pi-times" aria-label="Close Reader"></i>
</button>
</div>
@@ -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<void>();
@Output() showControls = new EventEmitter<void>();
@Output() showMetadata = new EventEmitter<void>();
@Output() createBookmark = new EventEmitter<void>();
@Output() close = new EventEmitter<void>();
@Output() toggleDarkMode = new EventEmitter<void>();
@Output() increaseFontSize = new EventEmitter<void>();
@Output() decreaseFontSize = new EventEmitter<void>();
@Output() increaseLineHeight = new EventEmitter<void>();
@Output() decreaseLineHeight = new EventEmitter<void>();
@Output() setFlow = new EventEmitter<'paginated' | 'scrolled'>();
get headerVisible(): boolean {
return this.forceVisible;
}
}
@@ -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);
}
}
@@ -1,104 +0,0 @@
<div class="dialog-overlay"
(click)="onOverlayClick()"
[class.closing]="closing">
<div class="sidebar"
(click)="$event.stopPropagation()"
[class.closing]="closing">
<div class="sidebar-header">
<div class="sidebar-header-book">
@if (bookCoverUrl) {
<img
[src]="bookCoverUrl"
alt="Book cover"
class="sidebar-book-cover clickable"
(click)="onCoverClick()"
role="button"
tabindex="0"
(keydown.enter)="onCoverClick()"
(keydown.space)="onCoverClick()"
title="View book details"
/>
}
<div class="sidebar-book-meta">
<div class="sidebar-book-title ellipsis">{{ bookTitle }}</div>
@if (bookAuthors) {
<div class="sidebar-book-authors ellipsis">{{ bookAuthors }}</div>
}
</div>
</div>
</div>
<div class="sidebar-tabs">
<button
class="tab-btn"
[class.active]="activeTab === 'chapters'"
(click)="activeTab = 'chapters'"
aria-label="Chapters"
>
<i class="pi pi-book tab-icon"></i>
<span class="tab-label">Chapters</span>
</button>
<button
class="tab-btn"
[class.active]="activeTab === 'bookmarks'"
(click)="activeTab = 'bookmarks'"
aria-label="Bookmarks"
>
<i class="pi pi-bookmark tab-icon"></i>
<span class="tab-label">Bookmarks</span>
</button>
</div>
<div class="sidebar-body">
@switch (activeTab) {
@case ('chapters') {
<ul class="chapter-list">
@for (chapter of chapters; track chapter.href) {
<ng-container *ngTemplateOutlet="chapterNode; context: { $implicit: chapter, level: 0 }"></ng-container>
}
</ul>
<ng-template #chapterNode let-chapter let-level="level">
<li>
<div class="chapter-row"
[class.has-subchapters]="chapter.subitems?.length"
[class.active]="isChapterActive(chapter.href)"
[style.paddingLeft.px]="12 + (level * 16)"
(click)="chapter.subitems?.length ? toggleChapterExpand(chapter.href) : onChapterClick(chapter.href)">
<span class="chapter-label ellipsis">{{ chapter.label }}</span>
@if (chapter.subitems?.length) {
<span class="accordion-icon" [class.expanded]="isChapterExpanded(chapter.href)">
<i class="pi" [ngClass]="isChapterExpanded(chapter.href) ? 'pi-chevron-down' : 'pi-chevron-right'"></i>
</span>
}
</div>
@if (chapter.subitems?.length && isChapterExpanded(chapter.href)) {
<ul class="subchapter-list">
@for (sub of chapter.subitems; track sub.href) {
<ng-container *ngTemplateOutlet="chapterNode; context: { $implicit: sub, level: level + 1 }"></ng-container>
}
</ul>
}
</li>
</ng-template>
}
@case ('bookmarks') {
@if (bookmarks.length > 0) {
<ul>
@for (bookmark of bookmarks; track bookmark.id) {
<li class="bookmark-item" (click)="onBookmarkClick(bookmark.cfi)">
<div class="bookmark-info">
<div class="bookmark-title ellipsis">{{ bookmark.title }}</div>
<div class="bookmark-date">{{ bookmark.createdAt | date: 'short' }}</div>
</div>
<button class="bookmark-delete-btn" (click)="onDeleteBookmark($event, bookmark.id)" aria-label="Delete bookmark">
&times;
</button>
</li>
}
</ul>
} @else {
<div class="empty-tab">No bookmarks yet.</div>
}
}
}
</div>
</div>
</div>
@@ -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;
}
}
@@ -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<void>();
@Output() chapterClick = new EventEmitter<string>();
@Output() bookmarkClick = new EventEmitter<string>();
@Output() deleteBookmark = new EventEmitter<number>();
@Output() coverClick = new EventEmitter<void>();
private urlHelperService = inject(UrlHelperService);
activeTab: 'chapters' | 'bookmarks' | 'annotation' = 'chapters';
closing = false;
bookCoverUrl: string | null = null;
expandedChapters = new Set<string>();
ngOnChanges(changes: SimpleChanges): void {
if (changes['bookId'] || changes['coverUpdatedOn']) {
this.bookCoverUrl = this.bookId
? this.urlHelperService.getThumbnailUrl(this.bookId, this.coverUpdatedOn)
: null;
}
if (changes['currentChapterHref']) {
if (this.currentChapterHref) {
this.autoExpandCurrentChapter();
}
}
}
private autoExpandCurrentChapter(): void {
if (!this.currentChapterHref) return;
const expandParents = (items: TocItem[], parents: string[] = []): boolean => {
for (const item of items) {
const currentParents = [...parents, item.href];
const normalizedItemHref = item.href.split('#')[0].replace(/^\//, '');
const normalizedCurrentHref = this.currentChapterHref!.split('#')[0].replace(/^\//, '');
if (normalizedItemHref === normalizedCurrentHref || item.href === this.currentChapterHref) {
parents.forEach(parentHref => this.expandedChapters.add(parentHref));
return true;
}
if (item.subitems?.length) {
if (expandParents(item.subitems, currentParents)) {
return true;
}
}
}
return false;
};
expandParents(this.chapters);
}
private closeWithAnimation(callback?: () => void) {
this.closing = true;
setTimeout(() => {
this.closing = false;
if (callback) callback();
this.close.emit();
}, 250);
}
onChapterClick(href: string) {
this.closeWithAnimation(() => this.chapterClick.emit(href));
}
onBookmarkClick(cfi: string) {
this.closeWithAnimation(() => this.bookmarkClick.emit(cfi));
}
onDeleteBookmark(event: MouseEvent, bookmarkId: number) {
event.stopPropagation();
this.deleteBookmark.emit(bookmarkId);
}
onCoverClick() {
this.closeWithAnimation(() => this.coverClick.emit());
}
onOverlayClick() {
this.closeWithAnimation();
}
toggleChapterExpand(href: string) {
if (this.expandedChapters.has(href)) {
this.expandedChapters.delete(href);
} else {
this.expandedChapters.add(href);
}
}
isChapterExpanded(href: string): boolean {
return this.expandedChapters.has(href);
}
isChapterActive(href: string): boolean {
if (!this.currentChapterHref) return false;
const normalizedItemHref = href.split('#')[0].replace(/^\//, '');
const normalizedCurrentHref = this.currentChapterHref.split('#')[0].replace(/^\//, '');
return normalizedItemHref === normalizedCurrentHref || href === this.currentChapterHref;
}
}
@@ -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 {
@@ -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<ReaderIconName, IconPath[]> = {
// 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: `
<svg
[attr.width]="size"
[attr.height]="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
[attr.stroke-width]="strokeWidth"
stroke-linecap="round"
stroke-linejoin="round"
[class]="className">
@for (path of paths; track $index) {
@switch (path.type) {
@case ('line') {
<line
[attr.x1]="getLineCoords(path.d, 0)"
[attr.y1]="getLineCoords(path.d, 1)"
[attr.x2]="getLineCoords(path.d, 2)"
[attr.y2]="getLineCoords(path.d, 3)"/>
}
@case ('polyline') {
<polyline [attr.points]="path.d"/>
}
@default {
<path [attr.d]="path.d"/>
}
}
}
</svg>
`,
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';
}
}
@@ -0,0 +1,71 @@
@if (visible) {
<div class="popup-backdrop" (click)="onDismiss($event)"></div>
<div class="text-selection-popup"
[class.show-below]="showBelow"
[style.left.px]="position.x"
[style.top.px]="position.y">
<button class="action-btn" (click)="onSelect()" title="Copy Text">
<app-reader-icon name="copy" [size]="16"></app-reader-icon>
</button>
<div class="divider"></div>
<button class="action-btn" (click)="onSearch()" title="Search in book">
<app-reader-icon name="search" [size]="16"></app-reader-icon>
</button>
<div class="divider"></div>
<div class="annotation-container">
<button class="action-btn" [class.active]="showAnnotationOptions" (click)="toggleAnnotationOptions()" title="Annotate">
<app-reader-icon name="edit" [size]="16"></app-reader-icon>
<app-reader-icon name="chevron-down" class="chevron" [class.open]="showAnnotationOptions" [size]="10"></app-reader-icon>
</button>
@if (showAnnotationOptions) {
<div class="annotation-options" [class.above]="!showBelow" [class.below]="showBelow">
<div class="style-buttons">
@for (style of styles; track style.value) {
<button
class="style-btn"
[class.selected]="selectedStyle === style.value"
[class.highlight-style]="style.value === 'highlight'"
[class.underline-style]="style.value === 'underline'"
[class.squiggly-style]="style.value === 'squiggly'"
[class.strikethrough-style]="style.value === 'strikethrough'"
[title]="style.label"
(click)="selectStyle(style.value)">
<span class="style-text">{{ style.icon }}</span>
</button>
}
</div>
<div class="color-buttons">
@for (color of colors; track color.value) {
<button
class="color-btn"
[style.--color]="color.value"
[class.selected]="selectedColor === color.value"
[title]="color.label"
(click)="selectColor(color.value)">
</button>
}
</div>
</div>
}
</div>
<div class="divider"></div>
<button class="action-btn" (click)="onNote()" title="Add Note">
<app-reader-icon name="note" [size]="16"></app-reader-icon>
</button>
@if (overlappingAnnotationId) {
<div class="divider"></div>
<button class="action-btn delete-btn" (click)="onDelete()" title="Delete Annotation">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
}
</div>
}
@@ -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);
}
}
@@ -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<TextSelectionAction>();
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;
}
}
@@ -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;
@@ -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<ProgressState>();
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;
}
}
@@ -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;
@@ -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',
@@ -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<Annotation[]> {
return this.http.get<Annotation[]>(`${this.url}/book/${bookId}`);
}
createAnnotation(request: CreateAnnotationRequest): Observable<Annotation> {
return this.http.post<Annotation>(this.url, request);
}
deleteAnnotation(annotationId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${annotationId}`);
}
updateAnnotation(annotationId: number, request: UpdateAnnotationRequest): Observable<Annotation> {
return this.http.put<Annotation>(`${this.url}/${annotationId}`, request);
}
}
@@ -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<BookNoteV2[]> {
return this.http.get<BookNoteV2[]>(`${this.url}/book/${bookId}`);
}
createNote(request: CreateBookNoteV2Request): Observable<BookNoteV2> {
return this.http.post<BookNoteV2>(this.url, request);
}
deleteNote(noteId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${noteId}`);
}
updateNote(noteId: number, request: UpdateBookNoteV2Request): Observable<BookNoteV2> {
return this.http.put<BookNoteV2>(`${this.url}/${noteId}`, request);
}
}