52 Commits

Author SHA1 Message Date
448cdcf9c2 new version: 0.3.0 2024-07-22 01:28:21 +03:00
9973637a92 feat: tab-bar 2024-07-22 01:26:19 +03:00
7904abd782 fix: reader scrolling 2024-07-22 00:42:21 +03:00
f53c36bea4 feat: search field 2024-07-22 00:40:40 +03:00
16d631423c feat: header refactor starting 2024-07-21 21:03:41 +03:00
c8168580d6 feat: dmca footer 2024-07-21 19:54:59 +03:00
f3a3344004 feat: started header changing 2024-07-20 23:47:35 +03:00
3713ac502c fix: manga page btns position 2024-07-20 23:08:04 +03:00
a81c7535c5 fix: clear search on going to main page 2024-07-20 23:01:22 +03:00
8c9efd4371 feat: click on manga page to change page 2024-07-20 22:36:31 +03:00
d710d6bac5 feat: popular titles on main page 2024-07-20 15:04:04 +03:00
6b209077ef feat: started popular titles on main page 2024-07-20 00:59:00 +03:00
2becf42487 feat: current page indicator 2024-07-19 15:57:36 +03:00
7b2c6d9fc8 feat: almost abstractions 2024-07-19 15:06:35 +03:00
00213d25a1 fix: manhwa scroll unloading pages 2024-07-18 16:51:30 +03:00
5465d1635c feat: loading indication 2024-07-18 16:50:48 +03:00
d414223df2 feat: auth btn in header 2024-07-18 16:35:46 +03:00
c427c6d0b4 feat: new token saving 2024-07-18 15:41:09 +03:00
4105933098 feat: manhwa scroll and cache pages rework 2024-07-17 23:46:33 +03:00
0fea62b639 todo: scroll offset 2024-07-17 17:00:07 +03:00
e040edb5bd feat: manhwa scroll 2024-07-17 16:58:22 +03:00
8c87401482 feat: manhwa check 2024-07-17 16:38:12 +03:00
c9c959ce76 feat: started work with directive 2024-07-15 00:05:58 +03:00
45389364ff feat: use map instead of interface 2024-07-14 23:50:16 +03:00
5a4206a81e fix(half): manhwa scroll 2024-07-14 01:05:16 +03:00
35ff603849 feat: scrolling manhwa 2024-07-12 01:32:32 +03:00
ccbd9b2f5c feat: started manhwa scrolling 2024-07-10 23:33:40 +03:00
03b200c829 feat: notification component 2024-07-10 23:02:14 +03:00
d1e32a94ca feat(rulib): token check 2024-07-10 19:22:53 +03:00
82a0ba102d feat: error in reader without auth 2024-07-10 16:51:26 +03:00
112e76ab45 feat: auth page 2024-07-10 16:35:14 +03:00
6833105604 feat: abstract classes and destroy subscriptions 2024-07-08 23:24:03 +03:00
9d2373a298 feat: auto-hide search 2024-07-07 23:48:02 +03:00
e6da8b17a7 feat: manhwa scroll 2024-07-07 23:23:40 +03:00
29fb7fd04d feat: chapter changing and manga scaling 2024-07-07 22:18:13 +03:00
8f5f12ad30 feat: caching pages 2024-07-07 00:48:54 +05:00
6bad651312 feat: show one page, nav buttons, cache pages 2024-07-06 22:20:43 +05:00
55e729422b feat: initial version of reader 2024-07-06 00:53:46 +03:00
2660aef473 feat: started details page 2024-07-05 20:07:13 +03:00
7eff09765b feat: getting details of manga 2024-07-05 13:24:36 +03:00
37149c83c4 feat: demo manga search 2024-07-05 01:04:49 +03:00
c7d76419f7 feat: started working on PWA app 2024-07-05 00:07:56 +03:00
6ddb3bad29 feat: search field 2024-07-05 00:06:48 +03:00
16a6a05d89 feat: tailwind and header 2024-07-04 16:58:32 +03:00
f1cbd9267c feat: started working on PWA app 2024-07-04 16:05:48 +03:00
1929760e82 New version: v0.2.3 2024-06-28 11:24:20 +03:00
167e5c4f65 Merge branch 'feature/show-row-name' into dev 2024-06-28 11:23:45 +03:00
40c9ca38b9 fix: file name on update 2024-06-28 11:23:33 +03:00
6bb99f6e0e feat: showing row name (in Japanese unfortunately) 2024-06-28 11:23:14 +03:00
53fee00315 New version: v0.2.2 2024-06-27 15:01:50 +03:00
c508caab7b Merge branch 'feature/i18n-translator' into dev 2024-06-27 14:52:16 +03:00
e90a1bb6ec feat: i18n for translator 2024-06-27 14:51:38 +03:00
93 changed files with 2468 additions and 56 deletions

View File

@@ -9,5 +9,8 @@
// "**/node_modules": true,
"**/.angular": true
},
"editor.formatOnSave": true
"editor.formatOnSave": true,
"cSpell.words": [
"Manhwa"
]
}

View File

@@ -0,0 +1,33 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"extends": ["plugin:@nx/angular", "plugin:@angular-eslint/template/process-inline-templates"],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
]
}
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}

View File

@@ -0,0 +1,29 @@
{
"$schema": "../../node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/**/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
]
}

View File

@@ -0,0 +1,75 @@
{
"name": "NwaifuAnime",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"prefix": "app",
"sourceRoot": "apps/NwaifuAnime/src",
"tags": [],
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:application",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/NwaifuAnime",
"index": "apps/NwaifuAnime/src/index.html",
"browser": "apps/NwaifuAnime/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/NwaifuAnime/tsconfig.app.json",
"inlineStyleLanguage": "less",
"assets": [
{
"glob": "**/*",
"input": "apps/NwaifuAnime/public"
}
],
"styles": ["apps/NwaifuAnime/src/styles.less"],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all",
"serviceWorker": "apps/NwaifuAnime/ngsw-config.json"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "NwaifuAnime:build:production"
},
"development": {
"buildTarget": "NwaifuAnime:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "NwaifuAnime:build"
}
},
"lint": {
"executor": "@nx/eslint:lint"
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@@ -0,0 +1,59 @@
{
"name": "NwaifuAnime",
"short_name": "NwaifuAnime",
"theme_color": "#1976d2",
"background_color": "#fafafa",
"display": "standalone",
"scope": "./",
"start_url": "./",
"icons": [
{
"src": "icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-96x96.png",
"sizes": "96x96",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-128x128.png",
"sizes": "128x128",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-144x144.png",
"sizes": "144x144",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-152x152.png",
"sizes": "152x152",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-384x384.png",
"sizes": "384x384",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable any"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,19 @@
@if (serviceWorkerEnabled) {
@if (hasUpdate) {
<h1>Update available</h1>
<button (click)="update()">Update</button>
} @else {
<h1>Update not available</h1>
}
}
<app-header></app-header>
<div class="md:h-12 h-16"></div>
<div
class="content overflow-y-auto md:h-[calc(100vh-3rem)] h-[calc(100vh-4rem)] flex flex-col justify-between flex-shrink-0"
>
<router-outlet></router-outlet>
<app-footer></app-footer>
<div class="md:min-h-0 min-h-16"></div>
</div>
<app-tab-bar></app-tab-bar>
<app-notification></app-notification>

View File

@@ -0,0 +1,3 @@
.content {
overflow-y: auto;
}

View File

@@ -0,0 +1,39 @@
import { Component } from "@angular/core";
import { RouterModule } from "@angular/router";
import { AppService } from "./app.service";
import { FooterComponent } from "./components/footer/footer.component";
import { HeaderComponent } from "./components/header/header.component";
import { NotificationComponent } from "./components/notification/notification.component";
import { TabBarComponent } from "./components/tab-bar/tab-bar.component";
@Component({
standalone: true,
imports: [
RouterModule,
HeaderComponent,
NotificationComponent,
NotificationComponent,
FooterComponent,
TabBarComponent,
],
selector: "app-root",
templateUrl: "./app.component.html",
styleUrl: "./app.component.less",
providers: [AppService],
})
export class AppComponent {
title = "NwaifuAnime";
constructor(private sw: AppService) {}
get hasUpdate() {
return this.sw.isUpdateAvailable;
}
update() {
this.sw.update();
}
get serviceWorkerEnabled() {
return this.sw.serviceWorkerEnabled;
}
}

View File

@@ -0,0 +1,22 @@
import { provideHttpClient, withFetch } from "@angular/common/http";
import { ApplicationConfig, isDevMode, provideZoneChangeDetection } from "@angular/core";
import { provideRouter } from "@angular/router";
import { provideServiceWorker } from "@angular/service-worker";
import { appRoutes } from "./app.routes";
import { Parser } from "./services/parsers/parser";
import { MangalibParserService } from "./services/parsers/rulib/mangalib.parser.service";
import { SlashlibParserService } from "./services/parsers/rulib/slashlib.parser.service";
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(appRoutes),
provideServiceWorker("ngsw-worker.js", {
enabled: !isDevMode(),
registrationStrategy: "registerWhenStable:30000",
}),
provideHttpClient(withFetch()),
{ provide: Parser, multi: true, useClass: MangalibParserService },
{ provide: Parser, multi: true, useClass: SlashlibParserService },
],
};

View File

@@ -0,0 +1,18 @@
import { Route } from "@angular/router";
import { AuthComponent } from "./components/auth/auth.component";
import { DetailComponent } from "./components/detail/detail.component";
import { HomeComponent } from "./components/home/home.component";
import { ReaderComponent } from "./components/reader/reader.component";
export const appRoutes: Route[] = [
{
path: "",
component: HomeComponent,
},
{ path: "detail", component: DetailComponent },
{ path: "reader", component: ReaderComponent },
{
path: "auth",
component: AuthComponent,
},
];

View File

@@ -0,0 +1,40 @@
import { Injectable } from "@angular/core";
import { SwUpdate } from "@angular/service-worker";
@Injectable({ providedIn: "root" })
export class AppService {
private hasUpdate = false;
constructor(private sw: SwUpdate) {
if (this.sw.isEnabled) {
console.log("service init");
this.sw.checkForUpdate();
this.sw.versionUpdates.subscribe((ev) => {
if (ev.type == "VERSION_DETECTED") {
console.log("update detected");
this.hasUpdate = true;
} else {
console.log("no update");
}
});
}
}
get isUpdateAvailable() {
return this.hasUpdate;
}
get serviceWorkerEnabled() {
return this.sw.isEnabled;
}
update() {
this.sw.activateUpdate().then((res) => {
if (res) {
console.log("updated");
this.hasUpdate = false;
window.location.reload();
}
});
}
}

View File

@@ -0,0 +1,46 @@
<div class="flex flex-col m-6">
<div class="mangalib-auth">
<h2>Авторизация в MangaLib</h2>
<ol class="list-decimal flex flex-col gap-4">
<li>
<p class="font-bold">Авторизация через токен</p>
<div class="flex flex-row gap-4">
<input
type="text"
placeholder="Token"
class="outline-none border-md border px-2"
#libSocialToken
/>
<button
type="button"
(click)="setLibSocialToken()"
class="hover:bg-slate-600 bg-slate-400 p-3 rounded-md text-white"
>
Сохранить
</button>
</div>
</li>
<li>
Вход через скрипт TamperMonkey. Если нет кнопки, значит вы не установили скрипт
<a
href="https://test-front.mangalib.me"
class="hover:bg-slate-600 bg-slate-400 p-3 rounded-md text-white tamperMonkey"
>
Вход
</a>
</li>
<li>
<div class="flex flex-row gap-3">
<button
type="button"
(click)="checkToken()"
class="hover:bg-slate-600 bg-slate-400 p-3 rounded-md text-white"
>
Проверить токен
</button>
<h3 class="self-center">{{ isRuLibAuth ? "Авторизован" : "Не авторизован" }}</h3>
</div>
</li>
</ol>
</div>
</div>

View File

@@ -0,0 +1,86 @@
import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from "@angular/core";
import { ActivatedRoute, Router, RouterLink } from "@angular/router";
import { Subject, takeUntil } from "rxjs";
import { NotificationService } from "../../services/notification/notification.service";
import { RulibAuthService } from "../../services/parsers/rulib/rulib.auth.service";
import { EAuthTokenService } from "./enum";
@Component({
selector: "app-auth",
templateUrl: "./auth.component.html",
styleUrls: ["./auth.component.less"],
standalone: true,
imports: [CommonModule, RouterLink],
})
export class AuthComponent implements AfterViewInit, OnDestroy {
private destroy$ = new Subject<void>();
@ViewChild("libSocialToken") libSocialToken: ElementRef<HTMLInputElement> | null = null;
isRuLibAuth = false;
constructor(
private route: ActivatedRoute,
private router: Router,
private rulibAuthService: RulibAuthService,
private notificationService: NotificationService,
) {}
private setToken(service: EAuthTokenService, token: string) {
switch (service) {
case EAuthTokenService.RULIB:
this.rulibAuthService
.setToken(token)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
if (data) {
this.router.navigate(["/"]);
this.notificationService.info("Успешная авторизация в RuLib!", "Вход");
} else {
this.router.navigate(["/", "auth"]);
this.notificationService.error(
"Не удалось авторизоваться в RuLib! Попробуйте ещё раз.",
"Вход",
4000,
);
}
});
break;
default:
this.router.navigate(["/", "auth"]);
this.notificationService.error("Неизвестный сервис авторизации!", "Вход");
return;
}
}
setLibSocialToken() {
if (this.libSocialToken) {
const token = this.libSocialToken.nativeElement.value;
this.setToken(EAuthTokenService.RULIB, token);
}
}
checkToken() {
this.rulibAuthService
.checkToken(this.rulibAuthService.getToken())
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
this.isRuLibAuth = data;
});
}
ngAfterViewInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const { token, service } = params;
if (token && service) {
this.setToken(service as EAuthTokenService, token);
}
});
if (this.libSocialToken) {
this.libSocialToken.nativeElement.value = this.rulibAuthService.getToken();
}
this.checkToken();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}

View File

@@ -0,0 +1,3 @@
export enum EAuthTokenService {
RULIB = "rulib",
}

View File

@@ -0,0 +1,44 @@
<div class="flex flex-col items-center">
@if (needAuth) {
<h1>Необходима авторизация</h1>
<a routerLink="/auth" class="text-center bg-slate-600 text-white p-3 rounded-md mb-4">Войти</a>
}
@if (detail_item) {
<h1>{{ detail_item.name }}</h1>
<h2>{{ detail_item.rus_name }}</h2>
<img [src]="detail_item.cover.default" [alt]="detail_item.slug" />
@if (!needAuth) {
<details class="w-full">
<summary class="text-center sticky top-0 bg-white z-10 py-2">
<h3>Главы</h3>
</summary>
<div class="flex flex-col items-center pb-16">
@for (chapter of chapters.data; track $index) {
<a
routerLink="/reader"
[queryParams]="{
url: detail_item.slug_url,
chapter: chapter.number,
volume: chapter.volume,
}"
[title]="chapter.name"
class="p-3 text-white bg-slate-600 w-[300px] mt-3 rounded-lg"
>
<h3>
<strong>{{ chapter.number }}.</strong> {{ chapter.name || "Нет названия" }}
</h3>
</a>
}
</div>
</details>
<a
routerLink="/reader"
class="p-3 text-white bg-slate-600 w-[300px] mt-5 rounded-lg text-center"
[queryParams]="{ url: detail_item.slug_url, volume: 1, chapter: 1 }"
>
Читать
</a>
}
}
</div>

View File

@@ -0,0 +1,71 @@
import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, OnDestroy } from "@angular/core";
import { ActivatedRoute, Router, RouterLink } from "@angular/router";
import { Subject, takeUntil } from "rxjs";
import { IRulibChaptersResult } from "../../services/parsers/rulib/rulib.chapters.dto";
import { Data } from "../../services/parsers/rulib/rulib.detail.dto";
import { SearchService } from "../../services/search.service";
@Component({
selector: "app-detail",
templateUrl: "./detail.component.html",
styleUrls: ["./detail.component.less"],
standalone: true,
imports: [CommonModule, RouterLink],
})
export class DetailComponent implements AfterViewInit, OnDestroy {
detail_item: Data | null = null;
chapters: IRulibChaptersResult = { data: [] };
needAuth: boolean = false;
private destroy$ = new Subject<void>();
constructor(
private route: ActivatedRoute,
private searchService: SearchService,
private router: Router,
) {}
private getDetails(url: string) {
this.searchService
.getDetails(url)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: (data) => {
this.detail_item = data.data;
},
error: (error) => {
console.log(error);
},
});
this.searchService
.getChapters(url)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: (data) => {
this.chapters = data;
if (data.data.length === 0) {
this.needAuth = true;
}
},
error: (error) => {
console.log(error);
},
});
}
ngAfterViewInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const url = params["url"];
if (url) {
this.searchService.setMangalibParser();
this.getDetails(url);
} else {
this.router.navigate(["/"]);
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}

View File

@@ -0,0 +1,19 @@
<div class="footer w-full border-t border-black bg-gray-300 pt-3 min-h-[15rem] mt-3">
<p class="text-3xl ps-[5rem]">DMCA Disclaimer</p>
<div class="footer-content h-full px-[5rem] flex flex-col gap-3">
<div class="block">
<p>На русском:</p>
<p>
Разработчики этого приложения не имеют никакого отношения к контенту, доступному в
приложении. Оно собрано из источников, свободно доступных через любой веб-браузер.
</p>
</div>
<div class="block">
<p>English:</p>
<p>
The developers of this application does not have any affiliation with the content available
in the app. It is collecting from the sources freely available through any web browser.
</p>
</div>
</div>
</div>

View File

@@ -0,0 +1,9 @@
import { Component } from "@angular/core";
@Component({
selector: "app-footer",
templateUrl: "./footer.component.html",
styleUrls: ["./footer.component.less"],
standalone: true,
})
export class FooterComponent {}

View File

@@ -0,0 +1,20 @@
<div
class="header fixed flex flex-col items-center px-2 justify-start gap-1 md:justify-between top-0 left-0 md:h-12 h-16 bg-gray-700 w-full md:flex-row"
>
<a routerLink="/" title="Main page"><p class="text-xl text-white">NwaifuAnime</p></a>
<app-search-field></app-search-field>
<button title="Profile" #profileBtn class="hidden md:block">
<div class="profile-btn bg-white rounded-full w-8 h-8 aspect-square ms-3">
<img src="pic/Blank-profile.png" alt="Profile pic" class="w-full h-full" />
</div>
</button>
</div>
<div
[class]="
'profile-menu hidden md:flex flex-col overflow-hidden z-20 rounded-md w-32 bg-white border border-black p-3 h-full fixed ' +
(menuOpened ? 'max-h-32 opacity-100' : 'max-h-0 opacity-0')
"
#profileMenu
>
<a routerLink="/auth" title="Auth page"><p class="hover:text-blue-400">Auth</p></a>
</div>

View File

@@ -0,0 +1,10 @@
.header {
transition: height 0.3s;
}
:host {
z-index: 20;
position: fixed;
}
.profile-menu {
transition: max-height 0.3s ease-in-out;
}

View File

@@ -0,0 +1,66 @@
import { CommonModule } from "@angular/common";
import {
AfterViewInit,
Component,
ElementRef,
HostListener,
OnDestroy,
ViewChild,
} from "@angular/core";
import { RouterLink } from "@angular/router";
import { Subject } from "rxjs";
import { SearchFieldComponent } from "../search-field/search-field.component";
@Component({
selector: "app-header",
templateUrl: "./header.component.html",
styleUrls: ["./header.component.less"],
standalone: true,
imports: [CommonModule, RouterLink, SearchFieldComponent],
})
export class HeaderComponent implements AfterViewInit, OnDestroy {
menuOpened = false;
@ViewChild("profileBtn") profileBtn: ElementRef<HTMLButtonElement> | null = null;
@ViewChild("profileMenu") profileMenu: ElementRef<HTMLDivElement> | null = null;
private destroy$ = new Subject<void>();
@HostListener("window:click", ["$event"])
toggleProfileMenu(event: MouseEvent) {
if (this.profileBtn && this.profileBtn.nativeElement.contains(event.target as Node)) {
this.menuOpened = !this.menuOpened;
console.log(this.menuOpened);
} else {
this.menuOpened = false;
}
}
ngAfterViewInit(): void {
this.moveProfileMenu();
}
@HostListener("window:resize")
moveProfileMenu() {
if (this.profileBtn && this.profileMenu) {
const btnRect = this.profileBtn.nativeElement.getBoundingClientRect();
const menuRect = this.profileMenu.nativeElement.getBoundingClientRect();
const menuWidth = menuRect.width;
const menuX = btnRect.left + btnRect.width / 2 - menuWidth * 0.8;
const menuY = btnRect.top + btnRect.height;
this.profileMenu.nativeElement.style.left = `${menuX}px`;
this.profileMenu.nativeElement.style.top = `calc(${menuY}px + 0.25rem)`;
}
}
get menuBtnClass(): string {
return `lni ${this.menuOpened ? "lni-close" : "lni-menu"} text-white`;
}
get searchBarClass(): string {
return `search-bar bg-slate-300 md:w-full w-full md:m-0 ms-2 me-2 md:h-6 h-10 md:flex justify-start flex-row items-center rounded-md ${this.menuOpened ? "flex" : "hidden"}`;
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}

View File

@@ -0,0 +1,58 @@
@if (!search) {
@if (loading) {
<p class="text-5xl text-center mb-16">Подождите...</p>
} @else {
<p class="text-5xl text-center mb-10">Популярное:</p>
<div class="flex flex-col gap-3 items-center w-full px-4 overflow-x-hidden">
@for (popular of popularItems; track popular[0]) {
<p class="text-5xl text-center">{{ popular[0] }}</p>
<div class="w-full overflow-x-auto py-3">
<div class="flex flex-row items-center gap-4 h-[400px] w-max">
@for (popularTitle of popular[1]; track popularTitle.id) {
<a routerLink="/detail" [queryParams]="{ url: popularTitle.slug_url }" class="h-full">
<div
class="flex flex-col justify-around border-black rounded-md p-4 w-[400px] items-center border h-full flex-shrink-0"
>
<img
[src]="popularTitle.cover.thumbnail"
[alt]="popularTitle.slug"
class="w-[200px] h-auto aspect-auto"
/>
<p>{{ popularTitle.rus_name }}</p>
</div>
</a>
}
</div>
</div>
}
</div>
}
} @else {
<div class="flex flex-col items-center w-full px-3 mt-3">
@if (loading) {
<h1>Loading...</h1>
}
@if (notFound && !loading) {
<h1>Not found</h1>
}
@for (item of items; track $index) {
<a
routerLink="/detail"
[queryParams]="{ url: item.slug_url }"
title="{{ item.name }}"
class="mb-6 max-w-[700px] w-full"
>
<div
class="card flex flex-col items-center border-black border-2 rounded-md p-4 w-full h-[350px]"
>
<h1>{{ item.rus_name }}</h1>
<img
[src]="item.cover.thumbnail"
[alt]="item.slug"
class="w-[200px] h-auto max-h-[300px] aspect-auto"
/>
</div>
</a>
}
</div>
}

View File

@@ -0,0 +1,3 @@
:host {
height: max-content;
}

View File

@@ -0,0 +1,92 @@
import { CommonModule } from "@angular/common";
import { Component, Input, OnDestroy, OnInit } from "@angular/core";
import { ActivatedRoute, RouterLink } from "@angular/router";
import { map, Subject, Subscription, takeUntil } from "rxjs";
import { IRuLIBPopular } from "../../services/parsers/rulib/rulib.popular.dto";
import { Datum } from "../../services/parsers/rulib/rulib.search.dto";
import { SearchService } from "../../services/search.service";
@Component({
standalone: true,
selector: "app-home",
templateUrl: "./home.component.html",
styleUrls: ["./home.component.less"],
imports: [CommonModule, RouterLink],
})
export class HomeComponent implements OnDestroy, OnInit {
@Input() items: Datum[] = [];
loading = false;
notFound = false;
search: string = "";
popularItemsMap: Map<string, IRuLIBPopular[]> = new Map<string, IRuLIBPopular[]>();
private destroy$ = new Subject<void>();
private popularSubscription = new Subscription();
constructor(
private searchService: SearchService,
private route: ActivatedRoute,
) {
this.searchService.setMangalibParser();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
this.popularSubscription.unsubscribe();
}
private getPopular(parserName: string) {
this.searchService
.getPopular()
.pipe(
map((data) => data as IRuLIBPopular[]),
takeUntil(this.destroy$),
)
.subscribe({
next: (data) => {
this.popularItemsMap.set(parserName, data);
this.loading = false;
},
error: (error) => {
console.error(error);
},
});
}
private getPopularMangalib() {
this.searchService.setMangalibParser();
this.getPopular(this.searchService.getRuLibName());
}
private getPopularSlashlib() {
this.searchService.setSlashlibParser();
this.getPopular(this.searchService.getRuLibName());
}
get popularItems() {
return Array.from(this.popularItemsMap.entries()).sort((a, b) => (a[0] > b[0] ? 1 : -1));
}
ngOnInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
this.search = params["search"] ?? "";
this.items = [];
this.loading = true;
if (this.search) {
this.searchService.setMangalibParser();
this.searchService
.search(this.search)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
this.loading = false;
this.items = data.data;
this.notFound = this.items.length === 0;
});
} else {
this.getPopularMangalib();
this.getPopularSlashlib();
}
});
}
}

View File

@@ -0,0 +1,12 @@
<div
class="notification-container fixed md:right-0 bottom-0 max-w-[100%] min-w-[100%] min-h-[8rem] h-[8rem] md:min-w-[20rem] px-3 pb-4"
[hidden]="!show_notification"
>
<div [class]="'notification rounded-md bg-white border-2 ' + borderColor + ' h-full'">
<div [class]="'head flex flex-row justify-between px-2 py-2 h-5 border-b-2 ' + borderColor">
<h3 class="self-center">{{ notification.name }}</h3>
<button class="self-center" (click)="closeNotification()" type="button">X</button>
</div>
<div class="notification-text mx-3 my-1">{{ notification.message }}</div>
</div>
</div>

View File

@@ -0,0 +1,53 @@
import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, OnDestroy } from "@angular/core";
import { Subject, takeUntil } from "rxjs";
import { INotification } from "../../services/notification/notification.dto";
import { NotificationService } from "../../services/notification/notification.service";
@Component({
standalone: true,
selector: "app-notification",
templateUrl: "./notification.component.html",
styleUrls: ["./notification.component.less"],
imports: [CommonModule],
})
export class NotificationComponent implements AfterViewInit, OnDestroy {
show_notification = false;
isError = false;
private closeNotificationTimer: ReturnType<typeof setTimeout> | null = null;
notification: INotification = { isError: false, message: "", name: "", time: 0 };
private destroy$ = new Subject<void>();
constructor(private notificationService: NotificationService) {}
ngAfterViewInit(): void {
this.notificationService.notification$
.asObservable()
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
if (!data) return;
this.notification = data;
this.show_notification = true;
if (this.closeNotificationTimer) {
clearTimeout(this.closeNotificationTimer);
}
this.closeNotificationTimer = setTimeout(() => {
this.show_notification = false;
}, data.time);
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
closeNotification() {
this.show_notification = false;
}
get borderColor(): string {
return this.notification.isError ? "border-red-600" : "border-green-600";
}
}

View File

@@ -0,0 +1,48 @@
<div
class="flex flex-row items-center justify-between me-4 max-w-[900px] relative -translate-x-[50%] left-[50%]"
>
<a
[routerLink]="['/', 'detail']"
[queryParams]="{ url: url }"
class="bg-slate-600 text-white rounded-lg p-3 m-4"
>
Назад к тайтлу
</a>
<h3>{{ currentChapterInfo?.number }}. {{ currentChapterInfo?.name || "Нет названия" }}</h3>
</div>
<div class="flex flex-col items-center">
@if (pages.length > 0 && currentPage) {
<div [class]="imageContainerClass">
@if (!isManhwa) {
<app-scale-image
[imageSrc]="currentPage.imageUrl"
(clickLeft)="prevPage()"
(clickRight)="nextPage()"
></app-scale-image>
} @else {
@for (page of manhwaPages; track page.id) {
<app-scale-image
[imageSrc]="page.imageUrl"
[host]="host"
(view)="loadPage(page.index)"
[hostScrollable]="isHostScrollable()"
></app-scale-image>
}
}
</div>
<div class="flex items-center justify-center space-x-4 mt-[6rem]">
<button (click)="prevPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg">
</button>
<p *ngIf="!isManhwa">{{ pages[currentPageIndex].slug }} / {{ pages.length }}</p>
<button (click)="nextPage()" class="p-3 text-white bg-slate-600 w-[100px] rounded-lg">
</button>
</div>
@if (isManhwa) {
<div class="hidden md:block md:fixed right-10 top-[50%]">
{{ currentPageIndex + 1 }} / {{ pages.length }}
</div>
}
}
</div>

View File

@@ -0,0 +1,245 @@
import { CommonModule, isPlatformBrowser } from "@angular/common";
import {
Component,
ElementRef,
HostListener,
Inject,
OnDestroy,
OnInit,
PLATFORM_ID,
} from "@angular/core";
import { ActivatedRoute, Router, RouterLink } from "@angular/router";
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 { CachedPage, CachedPages } from "./reader.dto";
@Component({
selector: "app-reader",
templateUrl: "./reader.component.html",
styleUrls: ["./reader.component.less"],
standalone: true,
imports: [CommonModule, ScaleImageComponent, RouterLink],
})
export class ReaderComponent implements OnInit, OnDestroy {
pages: Page[] = [];
currentPageIndex = 0;
cachedPages: CachedPages = new Map<number, CachedPage>();
imageUrl: string = "";
isManhwa = false;
currentChapterInfo: Chapter | null = null;
url = "";
private chaptersInfo: IRulibChapter[] = [];
private chapterNum: number = 0;
private chapterVol: number = 0;
private fromTowards = false;
private destroy$ = new Subject<void>();
constructor(
private route: ActivatedRoute,
private router: Router,
private searchService: SearchService,
public host: ElementRef,
@Inject(PLATFORM_ID) private platformId: object,
) {}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
get manhwaPages() {
return this.cachedPages.values();
}
ngOnInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const url = params["url"];
const chapter = params["chapter"];
const volume = params["volume"];
const fromTowards = params["from_towards"];
if (url && chapter && volume) {
this.searchService.setMangalibParser();
if (fromTowards) this.fromTowards = Boolean(+fromTowards);
else this.fromTowards = false;
this.chapterNum = +chapter;
this.chapterVol = +volume;
this.url = url;
this.searchService
.getChapters(url)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
this.chaptersInfo = data.data;
});
this.searchService
.isManhwa(url)
.pipe(takeUntil(this.destroy$))
.subscribe((data) => {
this.isManhwa = data;
this.loadChapter(url, chapter, volume);
});
} else {
this.router.navigate(["/"]);
}
});
}
public isHostScrollable(): boolean {
if (isPlatformBrowser(this.platformId)) {
const style = window.getComputedStyle(this.host.nativeElement);
return (
style.getPropertyValue("overflow") === "auto" ||
style.getPropertyValue("overflow-y") === "scroll"
);
}
return false;
}
backToTitle() {
this.router.navigate(["/", "detail"], { queryParams: { url: this.url } });
}
loadChapter(url: string, chapter: string, volume: string) {
this.searchService
.getChapter(url, chapter, volume)
.pipe(takeUntil(this.destroy$))
.subscribe({
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); // Загрузить последнюю страницу при открытии главы
} else this.loadPage(0); // Загрузить первую страницу при открытии главы
},
error: (error) => {
console.log(error);
this.router.navigate(["/", "detail"], { queryParams: { url: this.url } });
},
});
}
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++) {
const imgUrl = this.cachedPages.get(i)!.imageUrl;
this.cachedPages.get(i)!.imageUrl = "";
URL.revokeObjectURL(imgUrl);
}
}
loadPage(index: number) {
if (index >= 0 && index < this.pages.length) {
this.currentPageIndex = index;
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;
});
const nextChapterIndex = Math.min(thisChapterIndex + 1, this.chaptersInfo.length - 1);
const nextChapter = this.chaptersInfo[nextChapterIndex];
if (nextChapter !== this.chaptersInfo[thisChapterIndex]) {
this.cachedPages.clear();
this.router.navigate(["/", "reader"], {
queryParams: {
url: this.url,
chapter: nextChapter.number,
volume: nextChapter.volume,
},
});
}
} else if (index == -1) {
const thisChapterIndex = this.chaptersInfo.findIndex((chapter) => {
return +chapter.number === this.chapterNum && +chapter.volume === this.chapterVol;
});
const prevChapterIndex = Math.max(thisChapterIndex - 1, 0);
const prevChapter = this.chaptersInfo[prevChapterIndex];
if (prevChapter !== this.chaptersInfo[thisChapterIndex]) {
this.cachedPages.clear();
this.router.navigate(["/", "reader"], {
queryParams: {
url: this.url,
chapter: prevChapter.number,
volume: prevChapter.volume,
from_towards: 1,
},
});
}
}
}
@HostListener("window:keydown", ["$event"])
onKeydown(event: KeyboardEvent) {
if (event.key === "ArrowRight") {
this.nextPage();
} else if (event.key === "ArrowLeft") {
this.prevPage();
}
}
private getImageUrl(imageData?: Uint8Array): string {
if (!imageData) {
return "";
}
const blob = new Blob([imageData], { type: "image/jpeg" });
const urlCreator = window.URL || window.webkitURL;
return urlCreator.createObjectURL(blob);
}
nextPage() {
this.loadPage(this.currentPageIndex + 1);
}
prevPage() {
this.loadPage(this.currentPageIndex - 1);
}
get imageContainerClass() {
return `${this.isManhwa ? "h-auto" : "min-h-[70vh]"} w-screen md:w-[450px] flex flex-col`;
}
}

View File

@@ -0,0 +1,10 @@
import { Page } from "../../services/parsers/rulib/rulib.chapter.dto";
export interface CachedPage extends Page {
imageData?: Uint8Array;
imageUrl: string;
index: number;
isManhwa: boolean;
}
export type CachedPages = Map<number, CachedPage>;

View File

@@ -0,0 +1,7 @@
<div class="image-container" #container>
@if (imageSrc) {
<img #image [src]="imageSrc" (load)="onImageLoad()" alt="Manga page" class="cursor-pointer" />
} @else {
<div class="h-screen flex flex-col items-center justify-center"><h1>Loading...</h1></div>
}
</div>

View File

@@ -0,0 +1,12 @@
.image-container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}

View File

@@ -0,0 +1,125 @@
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
QueryList,
ViewChild,
ViewChildren,
} from "@angular/core";
import { Subject, Subscription, debounceTime, fromEvent, map, takeUntil } from "rxjs";
@Component({
selector: "app-scale-image",
templateUrl: "./scale-image.component.html",
styleUrls: ["./scale-image.component.less"],
standalone: true,
})
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;
@ViewChildren("image") imageList: QueryList<ElementRef<HTMLImageElement>> = new QueryList<
ElementRef<HTMLImageElement>
>();
@Output() view = new EventEmitter<void>();
@Output() clickLeft = new EventEmitter<void>();
@Output() clickRight = new EventEmitter<void>();
@Input() host: ElementRef | null = null;
@Input() hostScrollable: boolean = false;
private destroy$ = new Subject<void>();
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: "100px",
},
);
if (this.containerRef) this.observer.observe(this.containerRef.nativeElement);
}
if (!this.host) {
this.imageList.changes
.pipe<QueryList<ElementRef<HTMLImageElement>>>(takeUntil(this.destroy$))
.subscribe((imageList) => {
fromEvent(imageList.first.nativeElement, "click")
.pipe(
takeUntil(this.destroy$),
map((e) => e as MouseEvent),
)
.subscribe((e) => {
const target = e.target as HTMLImageElement;
const imageWidth = target.clientWidth;
const clickX = e.offsetX;
if (clickX < imageWidth / 2) this.clickLeft.emit();
else this.clickRight.emit();
});
});
}
// fromEvent(this.imageRef.first.nativeElement, "click")
// .pipe(takeUntil(this.destroy$))
// .subscribe((e) => {
// console.log(e);
// });
}
ngOnDestroy(): void {
if (this.resizeSubscription) this.resizeSubscription.unsubscribe();
if (this.observer) this.observer.disconnect();
this.destroy$.next();
this.destroy$.complete();
}
onImageLoad() {
this.scaleImage();
}
private setupResizeListener() {
this.resizeSubscription = fromEvent(window, "resize")
.pipe(debounceTime(200))
.subscribe(() => this.scaleImage());
}
private scaleImage() {
if (this.containerRef && this.imageRef) {
const container = this.containerRef.nativeElement;
const img = this.imageRef.nativeElement;
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const imgRatio = img.naturalWidth / img.naturalHeight;
const containerRatio = containerWidth / containerHeight;
let newWidth, newHeight;
if (imgRatio > containerRatio) {
newWidth = containerWidth;
newHeight = containerWidth / imgRatio;
} else {
newHeight = containerHeight;
newWidth = containerHeight * imgRatio;
}
newWidth = Math.min(newWidth, img.naturalWidth);
newHeight = Math.min(newHeight, img.naturalHeight);
if (img.naturalHeight / img.naturalWidth >= 5) {
img.style.width = "100%";
img.style.height = "auto";
} else {
img.style.width = `${newWidth}px`;
img.style.height = `${newHeight}px`;
}
}
}
}

View File

@@ -0,0 +1,21 @@
<div class="flex flex-row gap-3 justify-between items-center md:justify-end">
<div
[class]="
'input-block rounded-md bg-white transition-[width] delay-150 duration-300 ease-in-out h-full overflow-hidden flex justify-center items-center w-full ' +
(openSearchField ? 'md:w-[300px]' : 'md:w-0')
"
>
<input
type="search"
#searchInput
class="outline-none ps-1 text-sm leading-6 w-full border-0 bg-transparent border-r border-gray-700"
placeholder="Начать поиск"
(keydown.enter)="search()"
/>
</div>
<button (click)="toggleSearchField()" class="hidden md:block">
<div class="input-btn rounded-full w-8 h-8 bg-slate-400 flex justify-center items-center">
<i class="lni lni-search-alt text-white"></i>
</div>
</button>
</div>

View File

@@ -0,0 +1,3 @@
:host {
width: 100%;
}

View File

@@ -0,0 +1,64 @@
import { CommonModule } from "@angular/common";
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from "@angular/core";
import { ActivatedRoute, NavigationEnd, Router } from "@angular/router";
import { Subject, filter, takeUntil } from "rxjs";
@Component({
selector: "app-search-field",
standalone: true,
imports: [CommonModule],
templateUrl: "./search-field.component.html",
styleUrl: "./search-field.component.less",
})
export class SearchFieldComponent implements AfterViewInit, OnDestroy {
@ViewChild("searchInput") searchInput: ElementRef<HTMLInputElement> | null = null;
openSearchField = false;
private destroy$ = new Subject<void>();
constructor(
private route: ActivatedRoute,
private router: Router,
) {}
ngAfterViewInit(): void {
this.route.queryParams.pipe(takeUntil(this.destroy$)).subscribe((params) => {
const search = params["search"];
if (search && this.searchInput) {
this.searchInput.nativeElement.value = search;
this.openSearchField = true;
}
});
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
takeUntil(this.destroy$),
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.subscribe((event: any) => {
if (event.url === "/" && this.searchInput) {
this.searchInput.nativeElement.value = "";
this.openSearchField = false;
}
});
}
search() {
console.log(this.searchInput);
if (this.searchInput && this.searchInput.nativeElement.value)
this.router.navigate(["/"], {
queryParams: { search: this.searchInput.nativeElement.value },
});
}
toggleSearchField() {
this.openSearchField = !this.openSearchField;
if (this.openSearchField && this.searchInput) {
this.searchInput.nativeElement.focus();
}
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}

View File

@@ -0,0 +1,16 @@
<div
class="flex flex-row justify-start items-center md:hidden fixed bottom-0 w-full bg-gray-700 h-16 px-3"
>
@for (link of links; track link.link) {
<a [routerLink]="link.link">
<div class="tab-bar__item flex flex-col justify-center items-center h-full center w-16">
<i
[class]="
'text-3xl ' + link.line_icon + ' ' + (link.active ? 'text-white' : 'text-gray-500')
"
></i>
<span [class]="link.active ? 'text-white' : 'text-gray-500'">Auth</span>
</div>
</a>
}
</div>

View File

@@ -0,0 +1,3 @@
:host {
display: block;
}

View File

@@ -0,0 +1,41 @@
import { CommonModule } from "@angular/common";
import { Component, OnDestroy } from "@angular/core";
import { NavigationEnd, Router, RouterLink } from "@angular/router";
import { Subject, filter, takeUntil } from "rxjs";
import { ITab } from "./tab-bar.dto";
@Component({
selector: "app-tab-bar",
standalone: true,
imports: [CommonModule, RouterLink],
templateUrl: "./tab-bar.component.html",
styleUrl: "./tab-bar.component.less",
})
export class TabBarComponent implements OnDestroy {
links: ITab[] = [
{
link: "/auth",
line_icon: "lni lni-user",
name: "Auth",
active: false,
},
];
private destroy$ = new Subject<void>();
constructor(private router: Router) {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
takeUntil(this.destroy$),
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.subscribe((event: any) => {
this.links.forEach((link) => {
link.active = event.url.startsWith(link.link);
});
});
}
ngOnDestroy(): void {
throw new Error("Method not implemented.");
}
}

View File

@@ -0,0 +1,6 @@
export interface ITab {
link: string;
line_icon: string;
name: string;
active: boolean;
}

View File

@@ -0,0 +1,6 @@
export interface INotification {
message: string;
isError: boolean;
time: number;
name: string;
}

View File

@@ -0,0 +1,36 @@
import { Injectable, OnDestroy } from "@angular/core";
import { Subject } from "rxjs";
import { INotification } from "./notification.dto";
@Injectable({
providedIn: "root",
})
export class NotificationService implements OnDestroy {
readonly notification$ = new Subject<INotification>();
private sendNotification(message: INotification) {
this.notification$.next(message);
}
info(message: string, title: string = "", time = 3000) {
this.sendNotification({
message,
isError: false,
time: time,
name: title,
});
}
error(message: string, title: string = "", time = 3000) {
this.sendNotification({
message,
isError: true,
time: time,
name: title,
});
}
ngOnDestroy(): void {
this.notification$.complete();
}
}

View File

@@ -0,0 +1,19 @@
export function ParserDecorator({
site_name,
url,
nsfw = false,
site_id = 1,
}: {
site_name: string;
url: string;
nsfw?: boolean;
site_id?: number;
}) {
// eslint-disable-next-line @typescript-eslint/ban-types
return function (constructor: Function) {
constructor.prototype.site_name = site_name;
constructor.prototype.nsfw = nsfw;
constructor.prototype.api_url = url;
constructor.prototype.site_id = site_id;
};
}

View File

@@ -0,0 +1,4 @@
export enum EParser {
MangaLib = 0,
SlashLib = 1,
}

View File

@@ -0,0 +1,20 @@
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({ providedIn: "root" })
export abstract class Parser {
constructor(protected http: HttpClient) {}
protected abstract url: string;
abstract searchManga(query: string): Observable<object>;
abstract getDetails(slug_url: string): Observable<object>;
abstract getChapters(url: string): Observable<object>;
abstract getChapter(url: string, chapter: string, volume: string): Observable<object>;
abstract getPopular(): Observable<object[]>;
}

View File

@@ -0,0 +1,118 @@
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, catchError, map, throwError } from "rxjs";
import { Parser } from "../parser";
import { RulibAuthService } from "./rulib.auth.service";
import { IRulibChapterResult } from "./rulib.chapter.dto";
import { IRulibChaptersResult } from "./rulib.chapters.dto";
import { IRulibDetailResult } from "./rulib.detail.dto";
import { IRuLIBPopular } from "./rulib.popular.dto";
import { IRulibSearchResult } from "./rulib.search.dto";
@Injectable({
providedIn: "root",
})
export class LibSocialParserService extends Parser {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected url = (this as any).api_url;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private site_id = (this as any).site_id;
get imageServer() {
return "https://img33.imgslib.link";
}
constructor(
private rulibAuthService: RulibAuthService,
override http: HttpClient,
) {
super(http);
}
searchManga(query: string): Observable<IRulibSearchResult> {
return this.http
.get(
`${this.url}/api/manga?fields[]=rate_avg&fields[]=rate&q=${query}&site_id[]=${this.site_id}`,
)
.pipe(
map((data: object) => {
return data as IRulibSearchResult;
}),
catchError((error) => {
return throwError(() => `Now found ${error}`);
}),
);
}
getDetails(slug_url: string): Observable<IRulibDetailResult> {
return this.http
.get(
`${this.url}/api/manga/${slug_url}?fields[]=summary&fields[]=genres&fields[]=tags&fields[]=authors`,
{ headers: { Authorization: "Bearer " + this.rulibAuthService.getToken() } },
)
.pipe(
map((data: object) => {
return data as IRulibDetailResult;
}),
catchError((error) => {
return throwError(() => `Now found ${error}`);
}),
);
}
getChapters(url: string): Observable<IRulibChaptersResult> {
return this.http
.get(`${this.url}/api/manga/${url}/chapters`, {
headers: { Authorization: "Bearer " + this.rulibAuthService.getToken() },
})
.pipe(
map((data) => {
return data as IRulibChaptersResult;
}),
catchError((error) => {
return throwError(() => `Now found ${error}`);
}),
);
}
getChapter(url: string, chapter: string, volume: string): Observable<IRulibChapterResult> {
return this.http
.get(`${this.url}/api/manga/${url}/chapter?number=${chapter}&volume=${volume}`, {
headers: { Authorization: "Bearer " + this.rulibAuthService.getToken() },
})
.pipe(
map((data) => data as IRulibChapterResult),
catchError((error) => throwError(() => `Now found ${error}`)),
);
}
isManhwa(slug_url: string): Observable<boolean> {
return this.http
.get(
`${this.url}/api/manga/${slug_url}?fields[]=summary&fields[]=genres&fields[]=tags&fields[]=authors`,
)
.pipe(
map((data) => {
const res = data as IRulibDetailResult;
return [5, 6, 4].includes(res.data.type.id);
}),
catchError((error) => throwError(() => `Now found ${error}`)),
);
}
getPopular(): Observable<IRuLIBPopular[]> {
return this.http
.get<{ data: { popular: IRuLIBPopular[] } }>(`${this.url}/api/`, {
headers: {
Authorization: "Bearer " + this.rulibAuthService.getToken(),
"Site-Id": this.site_id,
},
})
.pipe(
map((data) => {
const res = data.data.popular;
return res;
}),
catchError((error) => throwError(() => `Now found ${error}`)),
);
}
}

View File

@@ -0,0 +1,10 @@
import { Injectable } from "@angular/core";
import { ParserDecorator } from "../decorators/parser.decorator";
import { ESiteUrls } from "../urls";
import { LibSocialParserService } from "./lib.social.parser.service";
@Injectable({
providedIn: "root",
})
@ParserDecorator({ site_name: "MangaLib", url: ESiteUrls.MANGALIB, site_id: 1 })
export class MangalibParserService extends LibSocialParserService {}

View File

@@ -0,0 +1,47 @@
import { HttpClient } from "@angular/common/http";
import { Injectable, OnDestroy } from "@angular/core";
import { Observable, Subject, catchError, map, of, takeUntil } from "rxjs";
import { IToken } from "../token.dto";
@Injectable({
providedIn: "root",
})
export class RulibAuthService implements OnDestroy {
private destroy$ = new Subject<void>();
private api_url = "https://api.lib.social";
constructor(private http: HttpClient) {}
setToken(token: string): Observable<boolean> {
return this.checkToken(token).pipe(
takeUntil(this.destroy$),
map((data) => {
if (!data) return false;
const token_data: IToken = JSON.parse(localStorage.getItem("token") ?? "{}");
token_data.rulib_token = token;
localStorage.setItem("token", JSON.stringify(token_data));
return true;
}),
);
}
getToken(): string {
const token_data: IToken = JSON.parse(localStorage.getItem("token") ?? "{}");
return token_data.rulib_token ?? "";
}
checkToken(token: string): Observable<boolean> {
return this.http
.get(this.api_url + "/api/auth/me", {
headers: { Authorization: `Bearer ${token}` },
})
.pipe(
takeUntil(this.destroy$),
map(() => true),
catchError(() => of(false)),
);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}

View File

@@ -0,0 +1,62 @@
export interface IRulibChapterResult {
data: Chapter;
}
export interface Chapter {
id: number;
type: string;
volume: string;
number: string;
number_secondary: string;
name: string;
slug: string;
branch_id: null;
manga_id: number;
created_at: Date;
moderated: Moderated;
likes_count: number;
teams: Team[];
pages: Page[];
}
export interface Moderated {
id: number;
label: string;
}
export interface Page {
id: number;
image: string;
slug: number;
external: number;
chunks: number;
chapter_id: number;
created_at: Date;
updated_at: UpdatedAt;
height: number;
width: number;
url: string;
ratio: string;
}
export enum UpdatedAt {
The0000011130T000000000000Z = "-000001-11-30T00:00:00.000000Z",
}
export interface Team {
id: number;
slug: string;
slug_url: string;
model: string;
name: string;
cover: Cover;
vk: null;
discord: null;
}
export interface Cover {
filename: null;
thumbnail: string;
default: string;
md: string;
}

View File

@@ -0,0 +1,85 @@
export interface IRulibChaptersResult {
data: IRulibChapter[];
}
export interface IRulibChapter {
id: number;
index: number;
item_number: number;
volume: string;
number: string;
number_secondary: string;
name: string;
branches_count: number;
branches: Branch[];
}
export interface Branch {
id: number;
branch_id: null;
created_at: Date;
teams: Team[];
user: User;
}
export interface Team {
id: number;
slug: Slug;
slug_url: SlugURL;
model: Model;
name: Name;
cover: Cover;
}
export interface Cover {
filename: null | string;
thumbnail: Thumbnail;
default: Default;
md: Default;
}
export enum Default {
StaticImagesPlaceholdersUserAvatarPNG = "/static/images/placeholders/user_avatar.png",
UploadsTeamAnyasyavaCoverJSazXO7JdAKV250X350Jpg = "/uploads/team/anyasyava/cover/jSazXO7JdAKV_250x350.jpg",
}
export enum Thumbnail {
StaticImagesPlaceholdersUserAvatarPNG = "/static/images/placeholders/user_avatar.png",
UploadsTeamAnyasyavaCoverJSazXO7JdAKVThumbJpg = "/uploads/team/anyasyava/cover/jSazXO7JdAKV_thumb.jpg",
}
export enum Model {
Team = "team",
}
export enum Name {
Abame = "abame",
Anyasyava = "ANYASYAVA",
Cabel = "Cabel",
Deadvm = "deadvm",
}
export enum Slug {
Abame = "abame",
Anyasyava = "anyasyava",
Cabel = "cabel",
Deadvm = "deadvm",
}
export enum SlugURL {
The13801Anyasyava = "13801--anyasyava",
The33106Abame = "33106--abame",
The42374Cabel = "42374--cabel",
The45635Deadvm = "45635--deadvm",
}
export interface User {
username: Username;
id: number;
}
export enum Username {
Deadvm = "deadvm",
Gjunyaa = "gjunyaa ❤️\ud83e\ude79",
Oksas = "oksas",
}

View File

@@ -0,0 +1,69 @@
export interface IRulibDetailResult {
data: Data;
meta: Meta;
}
export interface Data {
id: number;
name: string;
rus_name: string;
eng_name: string;
slug: string;
slug_url: string;
cover: Cover;
ageRestriction: AgeRestriction;
site: number;
type: AgeRestriction;
summary: string;
is_licensed: boolean;
genres: Genre[];
tags: Genre[];
authors: Author[];
model: string;
status: AgeRestriction;
releaseDateString: string;
}
export interface AgeRestriction {
id: number;
label: string;
}
export interface Author {
id: number;
slug: string;
slug_url: string;
model: string;
name: string;
rus_name: null;
alt_name: null;
cover: Cover;
subscription: Subscription;
confirmed: null;
user_id: number;
}
export interface Cover {
filename: null | string;
thumbnail: string;
default: string;
md: string;
}
export interface Subscription {
is_subscribed: boolean;
source_type: string;
source_id: number;
relation: null;
}
export interface Genre {
id: number;
name: string;
adult: boolean;
alert: boolean;
}
export interface Meta {
country: string;
}

View File

@@ -0,0 +1,61 @@
export interface IRuLIBPopular {
id: number;
name: string;
rus_name: string;
eng_name: string;
slug: string;
slug_url: string;
cover: Cover;
ageRestriction: AgeRestriction;
site: number;
type: AgeRestriction;
rating: Rating;
last_item_at: Date;
metadata: Metadata;
model: Model;
status: AgeRestriction;
releaseDateString: string;
}
export interface AgeRestriction {
id: number;
label: string;
}
export interface Cover {
filename: string;
thumbnail: string;
default: string;
md: string;
}
export interface Metadata {
last_item: LastItem;
}
export interface LastItem {
id: number;
number: string;
volume: number | string;
name: string;
branch_id: number | null;
status?: null;
type?: string;
number_secondary?: string;
slug?: number;
manga_id?: null;
created_at?: Date;
likes_count?: null;
}
export enum Model {
Manga = "manga",
}
export interface Rating {
average: string;
averageFormated: string;
votes: number;
votesFormated: string;
user: number;
}

View File

@@ -0,0 +1,79 @@
export interface IRulibSearchResult {
data: Datum[];
links: Links;
meta: Meta;
}
//TODO: Make normal namings
export interface Datum {
id: number;
name: string;
rus_name: string;
eng_name: string;
slug: string;
slug_url: string;
cover: Cover;
ageRestriction: AgeRestriction;
site: number;
type: AgeRestriction;
rating: Rating;
is_licensed: boolean;
model: Model;
status: AgeRestriction;
releaseDateString: string;
}
export interface AgeRestriction {
id: number;
label: Label;
}
export enum Label {
The12 = "12+",
The6 = "6+",
Завершён = "Завершён",
КомиксЗападный = "Комикс западный",
Манга = "Манга",
Манхва = "Манхва",
Маньхуа = "Маньхуа",
Нет = "Нет",
Онгоинг = "Онгоинг",
Приостановлен = "Приостановлен",
}
export interface Cover {
filename: string;
thumbnail: string;
default: string;
md: string;
}
export enum Model {
Manga = "manga",
}
export interface Rating {
average: string;
averageFormated: string;
votes: number;
votesFormated: string;
user: number;
}
export interface Links {
first: string;
last: null;
prev: null;
next: string;
}
export interface Meta {
current_page: number;
from: number;
path: string;
per_page: number;
to: number;
page: number;
has_next_page: boolean;
seed: string;
}

View File

@@ -0,0 +1,10 @@
import { Injectable } from "@angular/core";
import { ParserDecorator } from "../decorators/parser.decorator";
import { ESiteUrls } from "../urls";
import { LibSocialParserService } from "./lib.social.parser.service";
@Injectable({
providedIn: "root",
})
@ParserDecorator({ site_name: "Slashlib", url: ESiteUrls.LIB_SOCIAL, site_id: 2 })
export class SlashlibParserService extends LibSocialParserService {}

View File

@@ -0,0 +1,3 @@
export interface IToken {
rulib_token?: string;
}

View File

@@ -0,0 +1,5 @@
export enum ESiteUrls {
LIB_SOCIAL = "https://api.lib.social",
MANGALIB = "https://api.mangalib.me",
SLASHLIB = "https://api.slashlib.me",
}

View File

@@ -0,0 +1,89 @@
import { HttpClient } from "@angular/common/http";
import { Inject, Injectable } from "@angular/core";
import { Observable, map } from "rxjs";
import { EParser } from "./parsers/enums/parser";
import { Parser } from "./parsers/parser";
import { IRulibChapterResult } from "./parsers/rulib/rulib.chapter.dto";
import { IRulibChaptersResult } from "./parsers/rulib/rulib.chapters.dto";
import { IRulibDetailResult } from "./parsers/rulib/rulib.detail.dto";
import { IRulibSearchResult } from "./parsers/rulib/rulib.search.dto";
@Injectable({ providedIn: "root" })
export class SearchService {
private parser!: Parser;
constructor(
private http: HttpClient,
@Inject(Parser) private parsers: Parser[],
) {}
setMangalibParser() {
this.setParser(EParser.MangaLib);
}
setSlashlibParser() {
this.setParser(EParser.SlashLib);
}
private setParser(parser: EParser) {
this.parser = this.parsers[parser];
}
search(query: string): Observable<IRulibSearchResult> {
return this.parser.searchManga(query).pipe(
map((data) => {
return data as IRulibSearchResult;
}),
);
}
getDetails(slug_url: string): Observable<IRulibDetailResult> {
return this.parser.getDetails(slug_url).pipe(
map((data) => {
return data as IRulibDetailResult;
}),
);
}
getChapters(url: string): Observable<IRulibChaptersResult> {
return this.parser.getChapters(url).pipe(
map((data) => {
return data as IRulibChaptersResult;
}),
);
}
getChapter(url: string, chapter: string, volume: string): Observable<IRulibChapterResult> {
return this.parser.getChapter(url, chapter, volume).pipe(
map((data) => {
return data as IRulibChapterResult;
}),
);
}
getImageServer() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.parser as any).imageServer;
}
getImageData(imageUrl: string): Observable<Uint8Array> {
return this.http.get(imageUrl, { responseType: "arraybuffer" }).pipe(
map((arrayBuffer: ArrayBuffer) => {
return new Uint8Array(arrayBuffer);
}),
);
}
isManhwa(url: string): Observable<boolean> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.parser as any).isManhwa(url);
}
getPopular(): Observable<object[]> {
return this.parser.getPopular();
}
getRuLibName(): string {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (this.parser as any).site_name;
}
}

View File

@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>NwaifuAnime</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link href="https://cdn.lineicons.com/4.0/lineicons.css" rel="stylesheet" />
<link rel="manifest" href="manifest.webmanifest" />
<meta name="theme-color" content="#1976d2" />
</head>
<body>
<app-root></app-root>
<noscript>Please enable JavaScript to continue using this application.</noscript>
</body>
</html>

View File

@@ -0,0 +1,5 @@
import { bootstrapApplication } from "@angular/platform-browser";
import { appConfig } from "./app/app.config";
import { AppComponent } from "./app/app.component";
bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));

View File

@@ -0,0 +1,6 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
overflow-y: hidden;
}

View File

@@ -0,0 +1,14 @@
const { createGlobPatternsForDependencies } = require("@nx/angular/tailwind");
const { join } = require("path");
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
join(__dirname, "src/**/!(*.stories|*.spec).{ts,html}"),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
plugins: [],
};

View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": []
},
"files": ["src/main.ts"],
"include": ["src/**/*.d.ts"],
"exclude": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts"]
}

View File

@@ -0,0 +1,6 @@
{
"extends": "./tsconfig.json",
"include": ["src/**/*.ts"],
"compilerOptions": {},
"exclude": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts"]
}

View File

@@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "es2022",
"useDefineForClassFields": false,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.editor.json"
},
{
"path": "./tsconfig.app.json"
}
],
"extends": "../../tsconfig.base.json",
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@@ -1,6 +1,6 @@
@if (elements_data.length) {
<h1>Всего: {{ elements_data.length }}</h1>
<h2>Файл: {{ fileName }}</h2>
<h1>{{ "ROW_COUNT_LABEL" | translate }}: {{ elements_data.length }}</h1>
<h2>{{ "FILE_NAME_LABEL" | translate }}: {{ fileName }}</h2>
}
<div id="elements">
@for (item of elements_data; track $index) {

View File

@@ -1,5 +1,6 @@
import { CommonModule } from "@angular/common";
import { Component, Input, OnInit, QueryList, ViewChildren } from "@angular/core";
import { AfterViewInit, Component, Input, QueryList, ViewChildren } from "@angular/core";
import { TranslationPipe } from "../../../../pipes/translation.pipe";
import { NpsFile, TranslateData } from "../../dto/translate_data.dto";
import { TranslateBlockComponent } from "../translate_block/translate_block.component";
@@ -8,9 +9,9 @@ import { TranslateBlockComponent } from "../translate_block/translate_block.comp
templateUrl: "./text_list.component.html",
styleUrls: ["./text_list.component.scss"],
standalone: true,
imports: [CommonModule, TranslateBlockComponent],
imports: [CommonModule, TranslateBlockComponent, TranslationPipe],
})
export class TextListComponent implements OnInit {
export class TextListComponent implements AfterViewInit {
@ViewChildren("translateBlock") translate_blocks: QueryList<TranslateBlockComponent> | null =
null;
fileName = "";
@@ -18,13 +19,14 @@ export class TextListComponent implements OnInit {
@Input() set elements(el: TranslateData[]) {
this.elements_data = el;
localStorage.setItem("translations", JSON.stringify(this.elements_data));
this.ngAfterViewInit();
}
get elements() {
return this.elements_data;
}
ngOnInit(): void {
ngAfterViewInit(): void {
const data = localStorage.getItem("original_file");
if (data) {
const file: NpsFile = JSON.parse(data);

View File

@@ -1,6 +1,7 @@
<div class="element">
<h2>{{ index + 1 }}</h2>
<div class="fields">
<h2>{{ item.name }}</h2>
<nwui-textarea [contenteditable]="false">{{ item.english_text }}</nwui-textarea>
<nwui-textarea
#translatedText
@@ -11,8 +12,14 @@
>
</div>
<div class="btns">
<nwui-button (click)="sendToGoogleTranslate()" [disabled]="translateLoading">Translate</nwui-button>
<nwui-button (click)="isEditing = !isEditing" [disabled]="isEditing">Edit</nwui-button>
<nwui-button (click)="clear()" [disabled]="!item.translated_text.length">Clear</nwui-button>
<nwui-button (click)="sendToGoogleTranslate()" [disabled]="translateLoading">{{
"TRANSLATE_BTN" | translate
}}</nwui-button>
<nwui-button (click)="isEditing = !isEditing" [disabled]="isEditing">{{
"EDIT_BTN" | translate
}}</nwui-button>
<nwui-button (click)="clear()" [disabled]="!item.translated_text.length">{{
"CLEAR_ROW_BTN" | translate
}}</nwui-button>
</div>
</div>

View File

@@ -1,38 +1,45 @@
import { CommonModule } from '@angular/common';
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NWUIButtonComponent, NWUITextAreaComponent } from '@nwaifu-ui';
import { LocalStorageKeys } from '../../consts';
import { TranslateData } from '../../dto/translate_data.dto';
import { ETranslateService } from '../../services/translate.enums';
import { TranslateService } from '../../services/translate.service';
import { CommonModule } from "@angular/common";
import { Component, Input, OnInit, ViewChild } from "@angular/core";
import { NWUIButtonComponent, NWUITextAreaComponent } from "@nwaifu-ui";
import { TranslationPipe } from "../../../../pipes/translation.pipe";
import { LocalStorageKeys } from "../../consts";
import { TranslateData } from "../../dto/translate_data.dto";
import { ETranslateService } from "../../services/translate.enums";
import { TranslateService } from "../../services/translate.service";
@Component({
selector: 'app-translate-block',
templateUrl: './translate_block.component.html',
styleUrls: ['./translate_block.component.scss'],
selector: "app-translate-block",
templateUrl: "./translate_block.component.html",
styleUrls: ["./translate_block.component.scss"],
standalone: true,
imports: [CommonModule, NWUIButtonComponent, NWUITextAreaComponent],
imports: [CommonModule, NWUIButtonComponent, NWUITextAreaComponent, TranslationPipe],
providers: [TranslateService],
})
export class TranslateBlockComponent implements OnInit {
@ViewChild('translatedText') translatedText: NWUITextAreaComponent | null = null;
@Input({ required: true }) item: TranslateData = { english_text: '', translated_text: '' };
@ViewChild("translatedText") translatedText: NWUITextAreaComponent | null = null;
@Input({ required: true }) item: TranslateData = {
english_text: "",
translated_text: "",
name: "",
};
@Input({ required: true }) index = 0;
translateLoading = false;
isEditing = false;
saveChanges() {
const data: TranslateData[] = JSON.parse(localStorage.getItem(LocalStorageKeys.TRANSLATIONS) ?? '[]');
const data: TranslateData[] = JSON.parse(
localStorage.getItem(LocalStorageKeys.TRANSLATIONS) ?? "[]",
);
if (!data.length) {
alert('No data');
alert("No data");
return;
}
data[this.index] = this.item;
localStorage.setItem('translations', JSON.stringify(data));
localStorage.setItem("translations", JSON.stringify(data));
}
ngOnInit(): void {
this.isEditing = this.item.translated_text === '';
this.isEditing = this.item.translated_text === "";
}
constructor(private translateService: TranslateService) {}
@@ -40,7 +47,8 @@ export class TranslateBlockComponent implements OnInit {
private sendToTranslate(service: ETranslateService = ETranslateService.GOOGLE) {
this.translateLoading = true;
this.translateService.translate(this.item.english_text, service).subscribe((text) => {
if (this.translatedText) if (this.translatedText.ref) this.translatedText.ref.nativeElement.textContent = text;
if (this.translatedText)
if (this.translatedText.ref) this.translatedText.ref.nativeElement.textContent = text;
this.item.translated_text = text;
this.isEditing = false;
this.translateLoading = false;
@@ -62,14 +70,16 @@ export class TranslateBlockComponent implements OnInit {
saveTranslate(text: string) {
this.isEditing = false;
if (this.translatedText) if (this.translatedText.ref) this.translatedText.ref.nativeElement.textContent = '';
if (this.translatedText)
if (this.translatedText.ref) this.translatedText.ref.nativeElement.textContent = "";
this.item.translated_text = text;
this.saveChanges();
}
clear() {
this.item.translated_text = '';
this.item.translated_text = "";
this.isEditing = true;
if (this.translatedText) if (this.translatedText.ref) this.translatedText.ref.nativeElement.textContent = '';
if (this.translatedText)
if (this.translatedText.ref) this.translatedText.ref.nativeElement.textContent = "";
this.saveChanges();
}
}

View File

@@ -1,6 +1,7 @@
export interface TranslateData {
english_text: string;
translated_text: string;
name: string;
}
export interface NpsFile {
file_name: string;

View File

@@ -3,20 +3,33 @@ import { TranslateData } from "../dto/translate_data.dto";
export function parse(text: string): TranslateData[] {
// Find all TEXT attr data
const result: TranslateData[] = [];
const re = /<[^>]*TEXT="(?<textAttr>[^>"]+)"[^>]*>|<[^>]*>|\/\/.*|\s*\n\s*/gm;
const re = /^(?!\/\/)<[^>]*TEXT="(?<textAttr>[^>"]+)"[^>]*>/gim;
for (const match of text.matchAll(re)) {
console.log(match);
if (match.groups?.["textAttr"])
result.push({ english_text: match.groups?.["textAttr"], translated_text: "" });
result.push({
english_text: match.groups?.["textAttr"],
translated_text: "",
name: "Choice (without name)",
});
}
const replaced_text = text.replace(re, "\n").replace(/\s*\n\s*/gm, "\n");
result.push(
...replaced_text
.split("\n")
.map((line) => line.trim())
const name_re = /<voice name="(?<name>[^"]+)"[^>]*>(?<text>[\s\S]*?)(?=<voice|$)/gi;
for (const match of text.matchAll(name_re)) {
if (match.groups?.["name"] && match.groups?.["text"]) {
const name_text = match.groups?.["text"];
const name = match.groups?.["name"];
const re = /<[^>]*>|\/\/.*|\s*\n\s*/gm;
name_text
.split(re)
.filter((line) => line.length > 0)
.map((line) => ({ english_text: line, translated_text: "" })),
);
.map((line) => line.trim())
.forEach((line) => {
result.push({ english_text: line, translated_text: "", name: name });
});
}
}
console.log(result);
return result;
}

View File

@@ -1,7 +1,7 @@
<div class="btns">
<div id="op_btns">
<nwui-button (click)="fileInput.click()">
<span><i class="lni lni-upload"></i> Upload</span>
<span><i class="lni lni-upload"></i> {{ "UPLOAD_BTN" | translate }}</span>
<input
type="file"
(change)="submitFile($event)"
@@ -11,17 +11,17 @@
/>
</nwui-button>
<nwui-button (click)="onSaveClicked()">
<span><i class="lni lni-save"></i> Save</span>
<span><i class="lni lni-save"></i> {{ "SAVE_BTN" | translate }}</span>
</nwui-button>
@if (this.elements.length) {
<nwui-button (click)="clearAllTranslations()" [disabled]="!has_translations">
<span><i class="lni lni-trash-can"></i> Clear translations</span>
<span><i class="lni lni-trash-can"></i> {{ "CLEAR_TRANSLATIONS_BTN" | translate }}</span>
</nwui-button>
<nwui-button (click)="getAllTranslations()">
<span><i class="lni lni-google"></i> Translate all</span>
<span><i class="lni lni-google"></i> {{ "TRANSLATE_ALL_BTN" | translate }}</span>
</nwui-button>
<nwui-button (click)="onClearClicked()">
<span><i class="lni lni-trash-can"></i> Clear</span>
<span><i class="lni lni-trash-can"></i> {{ "CLEAR_BTN" | translate }}</span>
</nwui-button>
}
</div>

View File

@@ -3,6 +3,7 @@ import { AfterViewInit, Component, OnInit, ViewChild } from "@angular/core";
import { Router } from "@angular/router";
import { NWUIButtonComponent } from "@nwaifu-ui";
import { fromEvent, map } from "rxjs";
import { TranslationPipe } from "../../pipes/translation.pipe";
import { TextListComponent } from "./components/text_list/text_list.component";
import { LocalStorageKeys } from "./consts";
import { NpsFile, TranslateData } from "./dto/translate_data.dto";
@@ -10,7 +11,7 @@ import { saveOriginalFile } from "./lib/file_tools";
import { parse } from "./lib/parser";
@Component({
standalone: true,
imports: [TextListComponent, CommonModule, NWUIButtonComponent],
imports: [TextListComponent, CommonModule, NWUIButtonComponent, TranslationPipe],
selector: "app-nitroplus",
templateUrl: "./nitroplus-translator.component.html",
styleUrl: "./nitroplus-translator.component.less",

View File

@@ -5,5 +5,15 @@
"TELEGRAM_LABEL": "Telegram channel",
"GITHUB_LABEL": "Admin's Github",
"GITEA_LABEL": "Neuro LLC Gitea",
"SOURCE_CODE_TITLE": "Source code"
"SOURCE_CODE_TITLE": "Source code",
"UPLOAD_BTN": "Upload",
"SAVE_BTN": "Save",
"CLEAR_TRANSLATIONS_BTN": "Clear translations",
"CLEAR_BTN": "Clear",
"ROW_COUNT_LABEL": "Row count",
"FILE_NAME_LABEL": "File name",
"TRANSLATE_BTN": "Translate",
"EDIT_BTN": "Edit",
"CLEAR_ROW_BTN": "Clear",
"TRANSLATE_ALL_BTN": "Translate all"
}

View File

@@ -5,5 +5,15 @@
"TELEGRAM_LABEL": "Telegramチャンネル",
"GITHUB_LABEL": "管理者Github",
"GITEA_LABEL": "Neuro LLC Gitea",
"SOURCE_CODE_TITLE": "ソースコード"
"SOURCE_CODE_TITLE": "ソースコード",
"UPLOAD_BTN": "アップロード",
"SAVE_BTN": "保存",
"CLEAR_TRANSLATIONS_BTN": "翻訳をクリア",
"CLEAR_BTN": "クリア",
"ROW_COUNT_LABEL": "行数",
"FILE_NAME_LABEL": "ファイル名",
"TRANSLATE_BTN": "翻訳",
"EDIT_BTN": "編集",
"CLEAR_ROW_BTN": "クリア",
"TRANSLATE_ALL_BTN": "すべて翻訳"
}

View File

@@ -5,5 +5,15 @@
"TELEGRAM_LABEL": "Телеграм канал",
"GITHUB_LABEL": "Github админа",
"GITEA_LABEL": "Neuro LLC Gitea",
"SOURCE_CODE_TITLE": "Исходный код"
"SOURCE_CODE_TITLE": "Исходный код",
"UPLOAD_BTN": "Загрузить",
"SAVE_BTN": "Сохранить",
"CLEAR_TRANSLATIONS_BTN": "Очистить переводы",
"CLEAR_BTN": "Очистить",
"ROW_COUNT_LABEL": "Количество строк",
"FILE_NAME_LABEL": "Имя файла",
"TRANSLATE_BTN": "Перевести",
"EDIT_BTN": "Редактировать",
"CLEAR_ROW_BTN": "Очистить",
"TRANSLATE_ALL_BTN": "Перевести все"
}

BIN
bun.lockb

Binary file not shown.

View File

@@ -36,5 +36,10 @@
]
}
},
"nxCloudAccessToken": "${NX_CLOUD_ACCESS_TOKEN}"
"nxCloudAccessToken": "${NX_CLOUD_ACCESS_TOKEN}",
"generators": {
"@nx/angular:component": {
"style": "less"
}
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "nwaifu-web",
"version": "0.0.1",
"version": "0.3.0",
"scripts": {
"ng": "ng",
"start": "nx serve NwaifuWeb",
@@ -19,6 +19,7 @@
"@angular/platform-browser": "18.0.3",
"@angular/platform-browser-dynamic": "18.0.3",
"@angular/router": "18.0.3",
"@angular/service-worker": "18.0.3",
"@fortawesome/angular-fontawesome": "0.14.1",
"@fortawesome/fontawesome-svg-core": "^6.4.2",
"@fortawesome/free-brands-svg-icons": "^6.4.2",

View File

@@ -13,9 +13,7 @@
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"paths": {
"@nwaifu-ui": [
"nwaifu-ui/src/index.ts"
]
"@nwaifu-ui": ["nwaifu-ui/src/index.ts"]
},
"baseUrl": ".",
"rootDir": "."