feat: manhwa scroll and cache pages rework

This commit is contained in:
2024-07-17 23:46:33 +03:00
parent 0fea62b639
commit 4105933098
6 changed files with 106 additions and 183 deletions

View File

@@ -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);
}
}

View File

@@ -11,17 +11,21 @@
<h3>{{ currentChapterInfo?.number }}. {{ currentChapterInfo?.name || "Нет названия" }}</h3> <h3>{{ currentChapterInfo?.number }}. {{ currentChapterInfo?.name || "Нет названия" }}</h3>
</div> </div>
<div class="flex flex-col items-center"> <div class="flex flex-col items-center">
@if (pages.length > 0 && cachedPages.get(currentPageIndex)) { @if (pages.length > 0 && currentPage) {
<div [class]="imageContainerClass"> <div [class]="imageContainerClass">
@if (!isManhwa) { @if (!isManhwa) {
<app-scale-image [imageSrc]="imageUrl"></app-scale-image> <app-scale-image [imageSrc]="currentPage.imageUrl"></app-scale-image>
} @else { } @else {
@for (page of manhwaPages; track page.id) { @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>
<div #anchor></div>
<div class="flex items-center justify-center space-x-4 my-10"> <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"> <button (click)="prevPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg">

View File

@@ -3,19 +3,17 @@ import {
AfterViewInit, AfterViewInit,
Component, Component,
ElementRef, ElementRef,
HostListener,
Inject, Inject,
OnDestroy, OnDestroy,
PLATFORM_ID, PLATFORM_ID,
QueryList,
ViewChildren,
} from "@angular/core"; } from "@angular/core";
import { ActivatedRoute, Router, RouterLink } from "@angular/router"; 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 { Chapter, Page } from "../../services/parsers/rulib/rulib.chapter.dto";
import { IRulibChapter } from "../../services/parsers/rulib/rulib.chapters.dto"; import { IRulibChapter } from "../../services/parsers/rulib/rulib.chapters.dto";
import { SearchService } from "../../services/search.service"; import { SearchService } from "../../services/search.service";
import { ScaleImageComponent } from "../scale-image/scale-image.component"; import { ScaleImageComponent } from "../scale-image/scale-image.component";
import { LazyLoadDirective } from "./lazyscroll.directive";
import { CachedPage, CachedPages } from "./reader.dto"; import { CachedPage, CachedPages } from "./reader.dto";
@Component({ @Component({
@@ -23,7 +21,7 @@ import { CachedPage, CachedPages } from "./reader.dto";
templateUrl: "./reader.component.html", templateUrl: "./reader.component.html",
styleUrls: ["./reader.component.less"], styleUrls: ["./reader.component.less"],
standalone: true, standalone: true,
imports: [CommonModule, ScaleImageComponent, RouterLink, LazyLoadDirective], imports: [CommonModule, ScaleImageComponent, RouterLink],
}) })
export class ReaderComponent implements AfterViewInit, OnDestroy { export class ReaderComponent implements AfterViewInit, OnDestroy {
//FIXME: Scrolling to top when manhwa //FIXME: Scrolling to top when manhwa
@@ -39,21 +37,17 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
private chapterVol: number = 0; private chapterVol: number = 0;
private fromTowards = false; private fromTowards = false;
private destroy$ = new Subject<void>(); private destroy$ = new Subject<void>();
private scrollSubscription = new Subscription();
@ViewChildren("anchor") anchor: QueryList<ElementRef<HTMLDivElement>> = new QueryList();
private observer!: IntersectionObserver;
constructor( constructor(
private route: ActivatedRoute, private route: ActivatedRoute,
private router: Router, private router: Router,
private searchService: SearchService, private searchService: SearchService,
private host: ElementRef, public host: ElementRef,
@Inject(PLATFORM_ID) private platformId: object, @Inject(PLATFORM_ID) private platformId: object,
) {} ) {}
ngOnDestroy(): void { ngOnDestroy(): void {
this.destroy$.next(); this.destroy$.next();
this.destroy$.complete(); this.destroy$.complete();
if (this.observer) this.observer.disconnect();
} }
get manhwaPages() { get manhwaPages() {
@@ -72,7 +66,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
this.chapterNum = +chapter; this.chapterNum = +chapter;
this.chapterVol = +volume; this.chapterVol = +volume;
this.url = url; this.url = url;
this.loadChapter(url, chapter, volume);
this.searchService this.searchService
.getChapters(url) .getChapters(url)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
@@ -84,20 +77,7 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe((data) => { .subscribe((data) => {
this.isManhwa = data; this.isManhwa = data;
if (this.isManhwa) { this.loadChapter(url, chapter, volume);
//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);
});
}
}); });
} else { } else {
this.router.navigate(["/"]); this.router.navigate(["/"]);
@@ -105,10 +85,9 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
}); });
} }
private isHostScrollable(): boolean { public isHostScrollable(): boolean {
if (isPlatformBrowser(this.platformId)) { if (isPlatformBrowser(this.platformId)) {
const style = window.getComputedStyle(this.host.nativeElement); const style = window.getComputedStyle(this.host.nativeElement);
return ( return (
style.getPropertyValue("overflow") === "auto" || style.getPropertyValue("overflow") === "auto" ||
style.getPropertyValue("overflow-y") === "scroll" style.getPropertyValue("overflow-y") === "scroll"
@@ -118,48 +97,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
return false; 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() { backToTitle() {
this.router.navigate(["/", "detail"], { queryParams: { url: this.url } }); this.router.navigate(["/", "detail"], { queryParams: { url: this.url } });
} }
@@ -172,6 +109,15 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
next: (data) => { next: (data) => {
this.currentChapterInfo = data.data; this.currentChapterInfo = data.data;
this.pages = data.data.pages; 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) { if (this.fromTowards) {
this.currentPageIndex = this.pages.length - 1; this.currentPageIndex = this.pages.length - 1;
this.loadPage(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) { loadPage(index: number) {
if (index >= 0 && index < this.pages.length) { if (index >= 0 && index < this.pages.length) {
this.currentPageIndex = index; this.currentPageIndex = index;
this.cachePage(index); // Кэшируем текущую и соседние страницы this.cachePage(index);
if (!this.isManhwa) this.unloadCachedPages(index); // Сгружаем ненужные страницы из кэша this.clearCache(index - 2);
if (!this.isManhwa) { } else if (index == this.cachedPages.size) {
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) {
const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => { const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => {
return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol; 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) => { const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => {
return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol; return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol;
}); });
@@ -245,56 +211,16 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
} }
} }
// Кэширование текущей страницы и несколько соседних для ускорения процесса навигации по страницам @HostListener("window:keydown", ["$event"])
private cachePage(index: number) { onKeydown(event: KeyboardEvent) {
const startIndex = Math.max(0, index - 2); if (event.key === "ArrowRight") {
const endIndex = Math.min(this.pages.length - 1, index + 2); this.nextPage();
} else if (event.key === "ArrowLeft") {
for (let i = startIndex; i <= endIndex; i++) { this.prevPage();
if (!this.isPageCached(i)) {
this.fetchAndCachePage(i)
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
if (i === this.currentPageIndex) {
this.updateImage();
}
});
}
} }
} }
private isPageCached(index: number): boolean { private getImageUrl(imageData?: Uint8Array): string {
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 {
if (!imageData) { if (!imageData) {
return ""; return "";
} }
@@ -303,22 +229,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
return urlCreator.createObjectURL(blob); 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() { nextPage() {
this.loadPage(this.currentPageIndex + 1); this.loadPage(this.currentPageIndex + 1);
} }
@@ -328,6 +238,6 @@ export class ReaderComponent implements AfterViewInit, OnDestroy {
} }
get imageContainerClass() { 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`;
} }
} }

View File

@@ -3,7 +3,7 @@ import { Page } from "../../services/parsers/rulib/rulib.chapter.dto";
export interface CachedPage extends Page { export interface CachedPage extends Page {
imageData?: Uint8Array; imageData?: Uint8Array;
imageUrl: string; imageUrl: string;
index: number;
isManhwa: boolean; isManhwa: boolean;
} }

View File

@@ -1,3 +1,7 @@
<div class="image-container" #container> <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> </div>

View File

@@ -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"; import { Subscription, debounceTime, fromEvent } from "rxjs";
@Component({ @Component({
@@ -11,15 +20,30 @@ export class ScaleImageComponent implements AfterViewInit, OnDestroy {
@Input({ required: true }) imageSrc: string = ""; @Input({ required: true }) imageSrc: string = "";
@ViewChild("container", { static: true }) containerRef: ElementRef | null = null; @ViewChild("container", { static: true }) containerRef: ElementRef | null = null;
@ViewChild("image", { static: true }) imageRef: 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 resizeSubscription: Subscription = new Subscription();
private observer!: IntersectionObserver;
ngAfterViewInit(): void { ngAfterViewInit(): void {
this.setupResizeListener(); 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 { ngOnDestroy(): void {
if (this.resizeSubscription) this.resizeSubscription.unsubscribe(); if (this.resizeSubscription) this.resizeSubscription.unsubscribe();
if (this.observer) this.observer.disconnect();
} }
onImageLoad() { onImageLoad() {