feat: manhwa scroll and cache pages rework
This commit is contained in:
@@ -1,19 +0,0 @@
|
||||
import { Directive, ElementRef } from "@angular/core";
|
||||
|
||||
@Directive({
|
||||
selector: "[appLazyLoad]",
|
||||
standalone: true,
|
||||
})
|
||||
export class LazyLoadDirective {
|
||||
constructor({ nativeElement }: ElementRef) {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
console.log(entries);
|
||||
},
|
||||
{
|
||||
rootMargin: "1000px",
|
||||
},
|
||||
);
|
||||
observer.observe(nativeElement);
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,21 @@
|
||||
<h3>{{ currentChapterInfo?.number }}. {{ currentChapterInfo?.name || "Нет названия" }}</h3>
|
||||
</div>
|
||||
<div class="flex flex-col items-center">
|
||||
@if (pages.length > 0 && cachedPages.get(currentPageIndex)) {
|
||||
@if (pages.length > 0 && currentPage) {
|
||||
<div [class]="imageContainerClass">
|
||||
@if (!isManhwa) {
|
||||
<app-scale-image [imageSrc]="imageUrl"></app-scale-image>
|
||||
<app-scale-image [imageSrc]="currentPage.imageUrl"></app-scale-image>
|
||||
} @else {
|
||||
@for (page of manhwaPages; track page.id) {
|
||||
<app-scale-image [imageSrc]="page.imageUrl"></app-scale-image>
|
||||
<app-scale-image
|
||||
[imageSrc]="page.imageUrl"
|
||||
[host]="host"
|
||||
(view)="loadPage(page.index)"
|
||||
[hostScrollable]="isHostScrollable()"
|
||||
></app-scale-image>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div #anchor></div>
|
||||
<div class="flex items-center justify-center space-x-4 my-10">
|
||||
<button (click)="prevPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg">
|
||||
←
|
||||
|
||||
@@ -3,19 +3,17 @@ import {
|
||||
AfterViewInit,
|
||||
Component,
|
||||
ElementRef,
|
||||
HostListener,
|
||||
Inject,
|
||||
OnDestroy,
|
||||
PLATFORM_ID,
|
||||
QueryList,
|
||||
ViewChildren,
|
||||
} from "@angular/core";
|
||||
import { ActivatedRoute, Router, RouterLink } from "@angular/router";
|
||||
import { Observable, Subject, Subscription, fromEvent, map, takeUntil, throttleTime } from "rxjs";
|
||||
import { Subject, takeUntil } from "rxjs";
|
||||
import { Chapter, Page } from "../../services/parsers/rulib/rulib.chapter.dto";
|
||||
import { IRulibChapter } from "../../services/parsers/rulib/rulib.chapters.dto";
|
||||
import { SearchService } from "../../services/search.service";
|
||||
import { ScaleImageComponent } from "../scale-image/scale-image.component";
|
||||
import { LazyLoadDirective } from "./lazyscroll.directive";
|
||||
import { CachedPage, CachedPages } from "./reader.dto";
|
||||
|
||||
@Component({
|
||||
@@ -23,7 +21,7 @@ import { CachedPage, CachedPages } from "./reader.dto";
|
||||
templateUrl: "./reader.component.html",
|
||||
styleUrls: ["./reader.component.less"],
|
||||
standalone: true,
|
||||
imports: [CommonModule, ScaleImageComponent, RouterLink, LazyLoadDirective],
|
||||
imports: [CommonModule, ScaleImageComponent, RouterLink],
|
||||
})
|
||||
export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
//FIXME: Scrolling to top when manhwa
|
||||
@@ -39,21 +37,17 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
private chapterVol: number = 0;
|
||||
private fromTowards = false;
|
||||
private destroy$ = new Subject<void>();
|
||||
private scrollSubscription = new Subscription();
|
||||
@ViewChildren("anchor") anchor: QueryList<ElementRef<HTMLDivElement>> = new QueryList();
|
||||
private observer!: IntersectionObserver;
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private searchService: SearchService,
|
||||
private host: ElementRef,
|
||||
public host: ElementRef,
|
||||
@Inject(PLATFORM_ID) private platformId: object,
|
||||
) {}
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
if (this.observer) this.observer.disconnect();
|
||||
}
|
||||
|
||||
get manhwaPages() {
|
||||
@@ -72,7 +66,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
this.chapterNum = +chapter;
|
||||
this.chapterVol = +volume;
|
||||
this.url = url;
|
||||
this.loadChapter(url, chapter, volume);
|
||||
this.searchService
|
||||
.getChapters(url)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
@@ -84,20 +77,7 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe((data) => {
|
||||
this.isManhwa = data;
|
||||
if (this.isManhwa) {
|
||||
//TODO: scroll offset
|
||||
this.observer = new IntersectionObserver(
|
||||
([entry]) => entry.isIntersecting && this.testScrollEmitter(),
|
||||
{
|
||||
root: this.isHostScrollable() ? this.host.nativeElement : null,
|
||||
},
|
||||
);
|
||||
this.anchor.changes
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe((list: QueryList<ElementRef<HTMLDivElement>>) => {
|
||||
if (this.observer && list.first) this.observer.observe(list.first.nativeElement);
|
||||
});
|
||||
}
|
||||
this.loadChapter(url, chapter, volume);
|
||||
});
|
||||
} else {
|
||||
this.router.navigate(["/"]);
|
||||
@@ -105,10 +85,9 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private isHostScrollable(): boolean {
|
||||
public isHostScrollable(): boolean {
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
const style = window.getComputedStyle(this.host.nativeElement);
|
||||
|
||||
return (
|
||||
style.getPropertyValue("overflow") === "auto" ||
|
||||
style.getPropertyValue("overflow-y") === "scroll"
|
||||
@@ -118,48 +97,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
return false;
|
||||
}
|
||||
|
||||
private testScrollEmitter() {
|
||||
this.nextPage();
|
||||
}
|
||||
|
||||
private handleScrollManhwa(event: Event) {
|
||||
if (event.currentTarget) {
|
||||
if (
|
||||
(event.currentTarget as HTMLElement).scrollHeight -
|
||||
(event.currentTarget as HTMLElement).scrollTop <
|
||||
3000
|
||||
) {
|
||||
// this.loadPage(this.currentPageIndex + 1);
|
||||
console.log("load");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private initManhwaScroll() {
|
||||
const component = document.querySelector("app-reader");
|
||||
if (component && this.isManhwa) {
|
||||
this.scrollSubscription = fromEvent(component, "scroll")
|
||||
.pipe(
|
||||
throttleTime(300),
|
||||
map((data) => {
|
||||
console.log("throttle");
|
||||
return data;
|
||||
}),
|
||||
takeUntil(this.destroy$),
|
||||
)
|
||||
.subscribe((event) => {
|
||||
this.handleScrollManhwa(event);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private noManhwaScroll() {
|
||||
const component = document.querySelector("app-reader");
|
||||
if (component && !this.isManhwa) {
|
||||
this.scrollSubscription.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
backToTitle() {
|
||||
this.router.navigate(["/", "detail"], { queryParams: { url: this.url } });
|
||||
}
|
||||
@@ -172,6 +109,15 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
next: (data) => {
|
||||
this.currentChapterInfo = data.data;
|
||||
this.pages = data.data.pages;
|
||||
this.pages.forEach((page, index) => {
|
||||
this.cachedPages.set(index, {
|
||||
...page,
|
||||
imageUrl: "",
|
||||
isManhwa: this.isManhwa,
|
||||
index,
|
||||
});
|
||||
});
|
||||
this.loadPage(0);
|
||||
if (this.fromTowards) {
|
||||
this.currentPageIndex = this.pages.length - 1;
|
||||
this.loadPage(this.pages.length - 1); // Загрузить последнюю страницу при открытии главы
|
||||
@@ -184,32 +130,52 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
public intersectionLoadPage(id: number) {
|
||||
const data = Array.from(this.cachedPages.values()).find((page) => page.id === id)!;
|
||||
this.fetchPage(data);
|
||||
}
|
||||
|
||||
private loadPageByIndex(index: number) {
|
||||
const data = this.cachedPages.get(index)!;
|
||||
this.fetchPage(data);
|
||||
}
|
||||
|
||||
get currentPage() {
|
||||
return this.cachedPages.get(this.currentPageIndex);
|
||||
}
|
||||
|
||||
private fetchPage(page: CachedPage) {
|
||||
if (!page.imageUrl)
|
||||
this.searchService
|
||||
.getImageData(this.searchService.getImageServer() + page.url)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe((data) => {
|
||||
const url = this.getImageUrl(data);
|
||||
this.cachedPages.set(page.index, {
|
||||
...page,
|
||||
imageUrl: url,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private cachePage(index: number) {
|
||||
for (let i = index; i < Math.min(index + 2, this.cachedPages.size); i++) {
|
||||
this.loadPageByIndex(i);
|
||||
}
|
||||
}
|
||||
|
||||
private clearCache(index: number) {
|
||||
for (let i = 0; i <= index; i++) {
|
||||
this.cachedPages.get(i)!.imageUrl = "";
|
||||
}
|
||||
}
|
||||
|
||||
loadPage(index: number) {
|
||||
if (index >= 0 && index < this.pages.length) {
|
||||
this.currentPageIndex = index;
|
||||
this.cachePage(index); // Кэшируем текущую и соседние страницы
|
||||
if (!this.isManhwa) this.unloadCachedPages(index); // Сгружаем ненужные страницы из кэша
|
||||
if (!this.isManhwa) {
|
||||
const container = document.querySelector("app-reader");
|
||||
if (container) {
|
||||
container.scrollTo({
|
||||
top: 0,
|
||||
behavior: "smooth",
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!this.cachedPages.get(index)?.imageData) {
|
||||
// Если страница не закэширована, загружаем её
|
||||
this.fetchAndCachePage(index)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(() => {
|
||||
this.updateImage();
|
||||
});
|
||||
} else {
|
||||
// Если страница уже в кэше, просто обновляем изображение
|
||||
this.updateImage();
|
||||
}
|
||||
} else if (index == this.pages.length && !this.isManhwa) {
|
||||
this.cachePage(index);
|
||||
this.clearCache(index - 2);
|
||||
} else if (index == this.cachedPages.size) {
|
||||
const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => {
|
||||
return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol;
|
||||
});
|
||||
@@ -225,7 +191,7 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (index == -1 && !this.isManhwa) {
|
||||
} else if (index == -1) {
|
||||
const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => {
|
||||
return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol;
|
||||
});
|
||||
@@ -245,56 +211,16 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
// Кэширование текущей страницы и несколько соседних для ускорения процесса навигации по страницам
|
||||
private cachePage(index: number) {
|
||||
const startIndex = Math.max(0, index - 2);
|
||||
const endIndex = Math.min(this.pages.length - 1, index + 2);
|
||||
|
||||
for (let i = startIndex; i <= endIndex; i++) {
|
||||
if (!this.isPageCached(i)) {
|
||||
this.fetchAndCachePage(i)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(() => {
|
||||
if (i === this.currentPageIndex) {
|
||||
this.updateImage();
|
||||
}
|
||||
});
|
||||
}
|
||||
@HostListener("window:keydown", ["$event"])
|
||||
onKeydown(event: KeyboardEvent) {
|
||||
if (event.key === "ArrowRight") {
|
||||
this.nextPage();
|
||||
} else if (event.key === "ArrowLeft") {
|
||||
this.prevPage();
|
||||
}
|
||||
}
|
||||
|
||||
private isPageCached(index: number): boolean {
|
||||
return !!this.cachedPages.get(index)?.imageData;
|
||||
}
|
||||
|
||||
// Загрузка и сохранение изображения в кэш
|
||||
private fetchAndCachePage(index: number): Observable<void> {
|
||||
return this.searchService
|
||||
.getImageData(this.searchService.getImageServer() + this.pages[index].url)
|
||||
.pipe(
|
||||
map((imageData) => {
|
||||
const url = this.getImageUrl(imageData);
|
||||
this.cachedPages.set(index, {
|
||||
...this.pages[index],
|
||||
imageData,
|
||||
imageUrl: url,
|
||||
isManhwa: +this.pages[index].ratio < 0.5,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Выгрузка из кэша старых страниц
|
||||
private unloadCachedPages(index: number) {
|
||||
for (const key in this.cachedPages) {
|
||||
const pageIndex = +key;
|
||||
if (index - pageIndex > 2) {
|
||||
this.cachedPages.delete(pageIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getImageUrl(imageData?: Uint8Array): string {
|
||||
private getImageUrl(imageData?: Uint8Array): string {
|
||||
if (!imageData) {
|
||||
return "";
|
||||
}
|
||||
@@ -303,22 +229,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
return urlCreator.createObjectURL(blob);
|
||||
}
|
||||
|
||||
// Обновляем изображение на странице
|
||||
private updateImage() {
|
||||
const currentPage = this.cachedPages.get(this.currentPageIndex);
|
||||
if (currentPage && currentPage.imageData && !this.isManhwa) {
|
||||
const blob = new Blob([currentPage.imageData], { type: "image/jpeg" });
|
||||
const urlCreator = window.URL || window.webkitURL;
|
||||
this.imageUrl = urlCreator.createObjectURL(blob);
|
||||
const imageUrl = this.imageUrl;
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
URL.revokeObjectURL(imageUrl);
|
||||
};
|
||||
image.src = imageUrl;
|
||||
}
|
||||
}
|
||||
|
||||
nextPage() {
|
||||
this.loadPage(this.currentPageIndex + 1);
|
||||
}
|
||||
@@ -328,6 +238,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
|
||||
}
|
||||
|
||||
get imageContainerClass() {
|
||||
return `${this.isManhwa ? "h-auto" : "h-[70vh]"} w-[95vw] md:w-[700px] md:h-auto flex flex-col`;
|
||||
return `${this.isManhwa ? "h-auto" : "h-[70vh]"} w-[95vw] md:w-[450px] flex flex-col`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Page } from "../../services/parsers/rulib/rulib.chapter.dto";
|
||||
export interface CachedPage extends Page {
|
||||
imageData?: Uint8Array;
|
||||
imageUrl: string;
|
||||
|
||||
index: number;
|
||||
isManhwa: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
<div class="image-container" #container>
|
||||
<img #image [src]="imageSrc" (load)="onImageLoad()" alt="Manga page" />
|
||||
@if (imageSrc) {
|
||||
<img #image [src]="imageSrc" (load)="onImageLoad()" alt="Manga page" />
|
||||
} @else {
|
||||
<div class="h-screen flex flex-col items-center justify-center"><h1>Loading...</h1></div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild } from "@angular/core";
|
||||
import {
|
||||
AfterViewInit,
|
||||
Component,
|
||||
ElementRef,
|
||||
EventEmitter,
|
||||
Input,
|
||||
OnDestroy,
|
||||
Output,
|
||||
ViewChild,
|
||||
} from "@angular/core";
|
||||
import { Subscription, debounceTime, fromEvent } from "rxjs";
|
||||
|
||||
@Component({
|
||||
@@ -11,15 +20,30 @@ export class ScaleImageComponent implements AfterViewInit, OnDestroy {
|
||||
@Input({ required: true }) imageSrc: string = "";
|
||||
@ViewChild("container", { static: true }) containerRef: ElementRef | null = null;
|
||||
@ViewChild("image", { static: true }) imageRef: ElementRef | null = null;
|
||||
@Output() view = new EventEmitter<void>();
|
||||
@Input() host: ElementRef | null = null;
|
||||
@Input() hostScrollable: boolean = false;
|
||||
|
||||
private resizeSubscription: Subscription = new Subscription();
|
||||
private observer!: IntersectionObserver;
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
this.setupResizeListener();
|
||||
if (this.host) {
|
||||
this.observer = new IntersectionObserver(
|
||||
([entry]) => entry.isIntersecting && this.view.emit(),
|
||||
{
|
||||
root: this.hostScrollable ? this.host.nativeElement : null,
|
||||
rootMargin: "1000px",
|
||||
},
|
||||
);
|
||||
if (this.containerRef) this.observer.observe(this.containerRef.nativeElement);
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
if (this.resizeSubscription) this.resizeSubscription.unsubscribe();
|
||||
if (this.observer) this.observer.disconnect();
|
||||
}
|
||||
|
||||
onImageLoad() {
|
||||
|
||||
Reference in New Issue
Block a user