changed to a non nx monorepo
This commit is contained in:
@@ -1,12 +1,195 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { RouterOutlet } from '@angular/router';
|
||||
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { Auth } from '@angular/fire/auth';
|
||||
import { GoogleAuthProvider, signInWithPopup, UserCredential } from 'firebase/auth';
|
||||
import { PopoverComponent } from './components/popover.component';
|
||||
import { DeckListComponent } from './deck-list.component';
|
||||
import { ClickOutsideDirective } from './service/click-outside.directive';
|
||||
import { PopoverService } from './services/popover.service';
|
||||
import { UserService } from './services/user.service';
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
imports: [RouterOutlet],
|
||||
templateUrl: './app.component.html',
|
||||
styleUrl: './app.component.scss'
|
||||
template: `
|
||||
<div *ngIf="!isLoggedIn" class="min-h-screen flex flex-col items-center justify-center" style="background: rgba(0, 119, 179, 0.1)">
|
||||
<div class="text-center">
|
||||
<h1 class="text-5xl font-bold mb-4">Master Your Learning</h1>
|
||||
<p class="text-xl mb-8">Learn smarter, not harder. Start your journey today</p>
|
||||
<button (click)="loginWithGoogle()" class="bg-white text-blue-600 px-6 py-3 rounded-lg shadow-lg hover:bg-gray-100 transition duration-300 flex items-center justify-center">
|
||||
<svg class="w-6 h-6 mr-2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48">
|
||||
<path
|
||||
fill="#FFC107"
|
||||
d="M43.611 20.083H42V20H24v8h11.303c-1.649 4.657-6.08 8-11.303 8-6.627 0-12-5.373-12-12s5.373-12 12-12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 12.955 4 4 12.955 4 24s8.955 20 20 20 20-8.955 20-20c0-1.341-.138-2.65-.389-3.917z"
|
||||
/>
|
||||
<path fill="#FF3D00" d="M6.306 14.691l6.571 4.819C14.655 15.108 18.961 12 24 12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 16.318 4 9.656 8.337 6.306 14.691z" />
|
||||
<path fill="#4CAF50" d="M24 44c5.166 0 9.86-1.977 13.409-5.192l-6.19-5.238A11.91 11.91 0 0124 36c-5.202 0-9.619-3.317-11.283-7.946l-6.522 5.025C9.505 39.556 16.227 44 24 44z" />
|
||||
<path fill="#1976D2" d="M43.611 20.083H42V20H24v8h11.303a12.04 12.04 0 01-4.087 5.571l.003-.002 6.19 5.238C36.971 39.205 44 34 44 24c0-1.341-.138-2.65-.389-3.917z" />
|
||||
</svg>
|
||||
Login with Google
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div *ngIf="isLoggedIn" class="bg-white shadow mb-4">
|
||||
<div class="container mx-auto px-4 py-2 flex justify-between items-center">
|
||||
<!-- Logo und Name -->
|
||||
<div class="flex items-center space-x-2">
|
||||
<img src="../assets/logo.svg" alt="Logo" class="w-10 h-10" />
|
||||
<span class="text-xl font-bold">Haiky</span>
|
||||
</div>
|
||||
|
||||
<!-- Navigation -->
|
||||
<div class="hidden md:flex space-x-6">
|
||||
<span class="text-xl font-bold">Spaced Repetition Training</span>
|
||||
</div>
|
||||
|
||||
<!-- User-Bereich -->
|
||||
<div appClickOutside class="relative" (clickOutside)="showDropdown = false">
|
||||
<img *ngIf="photoURL" [src]="photoURL" alt="User Photo" class="w-10 h-10 rounded-full cursor-pointer" (click)="toggleDropdown()" referrerpolicy="no-referrer" crossorigin="anonymous" />
|
||||
<div *ngIf="!photoURL" class="image-placeholder w-10 h-10 rounded-full cursor-pointer bg-gray-300"></div>
|
||||
|
||||
<!-- Dropdown -->
|
||||
<div *ngIf="showDropdown" class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg z-10">
|
||||
<button (click)="logout()" class="block w-full text-left px-4 py-2 text-gray-700 hover:bg-gray-100">Logout</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<app-deck-list *ngIf="isLoggedIn"></app-deck-list>
|
||||
|
||||
<app-popover
|
||||
[visible]="popoverVisible"
|
||||
[title]="popoverTitle"
|
||||
[message]="popoverMessage"
|
||||
[showInput]="popoverShowInput"
|
||||
[showCancel]="popoverShowCancel"
|
||||
[inputValue]="popoverInputValue"
|
||||
[confirmText]="popoverConfirmText"
|
||||
(confirmed)="handleConfirm($event)"
|
||||
(canceled)="handleCancel()"
|
||||
></app-popover>
|
||||
`,
|
||||
standalone: true,
|
||||
styles: `
|
||||
img {
|
||||
border: 2px solid #fff;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
|
||||
img:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
/* Stile für das Dropdown-Menü */
|
||||
.dropdown {
|
||||
display: none;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
margin-top: 0.5rem;
|
||||
background-color: white;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.375rem;
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.dropdown button {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 0.5rem 1rem;
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
.dropdown button:hover {
|
||||
background-color: #f7fafc;
|
||||
}
|
||||
|
||||
`,
|
||||
imports: [CommonModule, DeckListComponent, ClickOutsideDirective, PopoverComponent],
|
||||
})
|
||||
export class AppComponent {
|
||||
title = 'haiky';
|
||||
isLoggedIn = false;
|
||||
private auth: Auth = inject(Auth);
|
||||
showDropdown = false;
|
||||
photoURL: string = 'https://placehold.co/40';
|
||||
// user: User | null = null;
|
||||
popoverVisible = false;
|
||||
popoverTitle = '';
|
||||
popoverMessage = '';
|
||||
popoverShowInput = false;
|
||||
popoverShowCancel = true;
|
||||
popoverInputValue = '';
|
||||
popoverConfirmText = 'Confirm';
|
||||
private confirmCallback?: (inputValue?: string) => void;
|
||||
private cancelCallback?: () => void;
|
||||
|
||||
constructor(public popoverService: PopoverService, private userService: UserService) {
|
||||
this.popoverService.popoverState$.subscribe(options => {
|
||||
this.popoverVisible = true;
|
||||
this.popoverTitle = options.title;
|
||||
this.popoverMessage = options.message;
|
||||
this.popoverShowInput = options.showInput;
|
||||
this.popoverShowCancel = options.showCancel;
|
||||
this.popoverInputValue = options.inputValue;
|
||||
this.popoverConfirmText = options.confirmText;
|
||||
this.confirmCallback = options.onConfirm;
|
||||
this.cancelCallback = options.onCancel;
|
||||
});
|
||||
}
|
||||
ngOnInit() {
|
||||
// Überprüfen des Login-Status beim Start der Anwendung
|
||||
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
|
||||
const accessToken = localStorage.getItem('accessToken');
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
this.photoURL = localStorage.getItem('photoURL');
|
||||
|
||||
if (isLoggedIn && accessToken && refreshToken) {
|
||||
this.isLoggedIn = true;
|
||||
}
|
||||
}
|
||||
|
||||
async loginWithGoogle() {
|
||||
const provider = new GoogleAuthProvider();
|
||||
try {
|
||||
const result: UserCredential = await signInWithPopup(this.auth, provider);
|
||||
this.isLoggedIn = true;
|
||||
this.photoURL = result.user.photoURL;
|
||||
|
||||
// Speichern des Login-Status und Tokens im Local Storage
|
||||
localStorage.setItem('isLoggedIn', 'true');
|
||||
localStorage.setItem('accessToken', await result.user.getIdToken());
|
||||
localStorage.setItem('refreshToken', result.user.refreshToken);
|
||||
localStorage.setItem('photoURL', result.user.photoURL);
|
||||
|
||||
this.showDropdown = false;
|
||||
|
||||
await this.userService.logIn({ name: result.user.displayName, email: result.user.email, sign_in_provider: result.providerId });
|
||||
|
||||
console.log('Logged in with Google', result.user);
|
||||
} catch (error) {
|
||||
console.error('Google Login failed', error);
|
||||
}
|
||||
}
|
||||
|
||||
logout() {
|
||||
this.isLoggedIn = false;
|
||||
localStorage.removeItem('isLoggedIn');
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
// Optional: Firebase-Logout durchführen
|
||||
this.auth.signOut();
|
||||
}
|
||||
toggleDropdown() {
|
||||
this.showDropdown = !this.showDropdown;
|
||||
}
|
||||
handleConfirm(inputValue?: string) {
|
||||
this.popoverVisible = false;
|
||||
if (this.confirmCallback) {
|
||||
this.confirmCallback(inputValue);
|
||||
}
|
||||
}
|
||||
|
||||
handleCancel() {
|
||||
this.popoverVisible = false;
|
||||
if (this.cancelCallback) {
|
||||
this.cancelCallback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
import { provideHttpClient, withInterceptors } from '@angular/common/http';
|
||||
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
|
||||
import { initializeApp, provideFirebaseApp } from '@angular/fire/app';
|
||||
import { getAuth, provideAuth } from '@angular/fire/auth';
|
||||
import { provideRouter } from '@angular/router';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
import { environment } from './environments/environment';
|
||||
import { authInterceptor } from './service/auth.interceptor';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes)]
|
||||
providers: [
|
||||
// {
|
||||
// provide: HTTP_INTERCEPTORS,
|
||||
// useClass: AuthInterceptor,
|
||||
// multi: true,
|
||||
// },
|
||||
provideFirebaseApp(() => initializeApp(environment.firebase)),
|
||||
provideAuth(() => getAuth()),
|
||||
provideZoneChangeDetection({ eventCoalescing: true }),
|
||||
provideRouter(routes),
|
||||
provideHttpClient(
|
||||
withInterceptors([authInterceptor]), // Hier wird der Interceptor registriert
|
||||
),
|
||||
],
|
||||
};
|
||||
|
||||
56
src/app/components/popover.component.ts
Normal file
56
src/app/components/popover.component.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
// popover.component.ts
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, EventEmitter, Input, Output } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
|
||||
@Component({
|
||||
selector: 'app-popover',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule],
|
||||
template: `
|
||||
<div class="fixed inset-0 bg-gray-500 bg-opacity-50 flex items-center justify-center z-50" *ngIf="visible">
|
||||
<div class="bg-white rounded-lg p-6 max-w-xs w-full shadow-lg border border-gray-200">
|
||||
<h3 class="text-lg font-semibold mb-4">{{ title }}</h3>
|
||||
|
||||
<p *ngIf="message" class="mb-4">{{ message }}</p>
|
||||
|
||||
<input *ngIf="showInput" type="text" class="w-full p-2 border rounded mb-4 focus:ring-2 focus:ring-blue-500 focus:border-transparent" [(ngModel)]="inputValue" (keyup.enter)="onConfirm()" autofocus />
|
||||
|
||||
<div class="flex justify-end space-x-2">
|
||||
@if(showCancel){
|
||||
<button (click)="onCancel()" class="px-4 py-2 rounded bg-gray-100 text-gray-700 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400">Cancel</button>
|
||||
}
|
||||
<button (click)="onConfirm()" class="px-4 py-2 rounded bg-blue-500 text-white hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
|
||||
{{ confirmText }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class PopoverComponent {
|
||||
@Input() title: string = '';
|
||||
@Input() message: string = '';
|
||||
@Input() showInput: boolean = false;
|
||||
@Input() showCancel: boolean = false;
|
||||
@Input() confirmText: string = 'Confirm';
|
||||
@Input() inputValue: string = '';
|
||||
@Input() visible: boolean = false;
|
||||
@Output() confirmed = new EventEmitter<string>();
|
||||
@Output() canceled = new EventEmitter<void>();
|
||||
|
||||
onConfirm() {
|
||||
this.confirmed.emit(this.inputValue);
|
||||
//this.reset();
|
||||
}
|
||||
|
||||
onCancel() {
|
||||
this.canceled.emit();
|
||||
//this.reset();
|
||||
}
|
||||
|
||||
private reset() {
|
||||
this.visible = false;
|
||||
this.inputValue = '';
|
||||
}
|
||||
}
|
||||
24
src/app/create-deck-modal/create-deck-modal.component.html
Normal file
24
src/app/create-deck-modal/create-deck-modal.component.html
Normal file
@@ -0,0 +1,24 @@
|
||||
<div #createDeckModal id="createDeckModal" tabindex="-1" aria-hidden="true" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full">
|
||||
<div class="relative w-full h-full max-w-md md:h-auto">
|
||||
<div class="relative bg-white rounded-lg shadow">
|
||||
<button type="button" class="absolute top-3 right-2.5 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center" (click)="closeModal()">
|
||||
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
|
||||
</svg>
|
||||
<span class="sr-only">Close</span>
|
||||
</button>
|
||||
<div class="p-6">
|
||||
<h3 class="mb-4 text-xl font-medium text-gray-900">Create New Deck</h3>
|
||||
<form (submit)="createDeck($event)">
|
||||
<div class="mb-4">
|
||||
<label for="deckName" class="block text-sm font-medium text-gray-700">Deck Name</label>
|
||||
<input type="text" id="deckName" [(ngModel)]="deckName" name="deckName" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" />
|
||||
</div>
|
||||
<button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
|
||||
Create
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
59
src/app/create-deck-modal/create-deck-modal.component.ts
Normal file
59
src/app/create-deck-modal/create-deck-modal.component.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { AfterViewInit, Component, ElementRef, EventEmitter, Output, ViewChild } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Modal } from 'flowbite';
|
||||
import { DeckService } from '../services/deck.service';
|
||||
import { PopoverService } from '../services/popover.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-create-deck-modal',
|
||||
templateUrl: './create-deck-modal.component.html',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule],
|
||||
})
|
||||
export class CreateDeckModalComponent implements AfterViewInit {
|
||||
@Output() deckCreated = new EventEmitter<void>();
|
||||
@ViewChild('createDeckModal') modalElement!: ElementRef;
|
||||
deckName: string = '';
|
||||
modal!: Modal;
|
||||
|
||||
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
this.modal = new Modal(this.modalElement.nativeElement);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.modal.show();
|
||||
}
|
||||
|
||||
createDeck(event: Event): void {
|
||||
event.preventDefault();
|
||||
if (this.deckName.trim() === '') {
|
||||
this.popoverService.show({
|
||||
title: 'Information',
|
||||
message: 'Please enter a deck name !',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.deckService.createDeck(this.deckName).subscribe({
|
||||
next: () => {
|
||||
this.deckName = '';
|
||||
this.deckCreated.emit();
|
||||
this.modal.hide();
|
||||
},
|
||||
error: err => {
|
||||
console.error('Error creating deck', err);
|
||||
this.popoverService.show({
|
||||
title: 'Error',
|
||||
message: 'Error creating deck.',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
closeModal(): void {
|
||||
this.modal.hide();
|
||||
}
|
||||
}
|
||||
144
src/app/deck-list.component.html
Normal file
144
src/app/deck-list.component.html
Normal file
@@ -0,0 +1,144 @@
|
||||
<div class="flex flex-col">
|
||||
<!-- Two-column layout -->
|
||||
<div *ngIf="!trainingsDeck" class="flex flex-col md:flex-row gap-4 mx-auto max-w-5xl">
|
||||
<!-- Left column: List of decks -->
|
||||
<div class="w-auto">
|
||||
<div class="bg-white shadow rounded-lg p-4">
|
||||
<div class="flex">
|
||||
<h2 class="text-xl font-semibold mb-4">Decks</h2>
|
||||
<button (click)="openCreateDeckModal()" class="text-gray-500 hover:text-gray-700 focus:outline-none flex items-start ml-2.5 translate-y-0.5">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="#2563eb">
|
||||
<circle cx="12" cy="12" r="9" stroke-width="2" />
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v8M8 12h8" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<div *ngFor="let deck of decks" class="flex justify-between items-center p-2 rounded hover:bg-gray-300 cursor-pointer" [class.bg-blue-200]="isDeckActive(deck)" (click)="toggleDeckExpansion(deck)">
|
||||
<div class="flex flex-col space-y-1">
|
||||
<div class="flex items-center space-x-2 whitespace-nowrap">
|
||||
<h3 class="font-medium">{{ deck.name }}</h3>
|
||||
<span class="text-gray-600">({{ deck.images.length }} Pics)</span>
|
||||
</div>
|
||||
<div class="text-sm text-gray-600">
|
||||
<div [ngClass]="{ 'text-blue-500 font-bold': isToday(getNextTrainingDate(deck)), 'text-rose-500 font-bold': isBeforeToday(getNextTrainingDate(deck)) }">
|
||||
Next training: {{ getNextTrainingString(deck) }}
|
||||
</div>
|
||||
<div>Words to review: {{ getWordsToReview(deck) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="text-gray-500 hover:text-gray-700 focus:outline-none">
|
||||
<svg *ngIf="!isDeckActive(deck)" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transform rotate-0 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
<svg *ngIf="isDeckActive(deck)" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transform rotate-180 transition-transform duration-200" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right column: Active deck details -->
|
||||
<div class="w-auto min-w-96" *ngIf="activeDeck">
|
||||
<div class="bg-white shadow rounded-lg p-6 border-dashed border-2 border-gray-300">
|
||||
<!-- Deck header -->
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<div class="flex items-center space-x-2">
|
||||
<h2 class="text-xl font-semibold">{{ activeDeck.name }}</h2>
|
||||
<span class="text-gray-600">({{ activeDeck.images.length }} images)</span>
|
||||
</div>
|
||||
<div class="flex space-x-2">
|
||||
<button (click)="openDeletePopover(activeDeck.name)" class="text-red-500 hover:text-red-700" title="Delete Deck">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<button (click)="openRenamePopover(activeDeck)" class="text-yellow-500 hover:text-yellow-700" title="Rename Deck">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Image list -->
|
||||
<ul class="mb-4">
|
||||
<li *ngFor="let image of activeDeck.images" class="flex justify-between items-center py-2 border-b last:border-b-0">
|
||||
<div class="flex items-center space-x-2">
|
||||
<div class="relative group">
|
||||
<div class="absolute left-0 bottom-full mb-2 w-48 bg-white border border-gray-300 rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 z-10 pointer-events-none">
|
||||
<img src="/images/{{ image.bildid }}/thumbnail.webp" alt="{{ image.name }}" class="w-full h-auto object-cover" />
|
||||
</div>
|
||||
<span class="font-medium cursor-pointer">{{ image.name }}</span>
|
||||
</div>
|
||||
<span class="text-gray-600">({{ image.boxes.length }} boxes)</span>
|
||||
</div>
|
||||
<div class="flex space-x-2">
|
||||
<button (click)="editImage(activeDeck, image)" class="text-blue-500 hover:text-blue-700" title="Edit Image">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 4H4v7m0 0l9-9 9 9M20 13v7h-7m0 0l-9-9-9 9" />
|
||||
</svg>
|
||||
</button>
|
||||
<button (click)="deleteImage(activeDeck, image)" class="text-red-500 hover:text-red-700" title="Delete Image">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<button (click)="openMoveImageModal(activeDeck, image)" class="text-yellow-500 hover:text-yellow-700" title="Move Image">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
</button>
|
||||
<button (click)="openRenameImagePopover(image)" class="text-yellow-500 hover:text-yellow-700" title="Rename Image">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="flex flex-row space-x-2 items-stretch">
|
||||
<button (click)="openTraining(activeDeck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 flex items-center justify-center whitespace-nowrap">Start Training</button>
|
||||
<div class="flex-1">
|
||||
<div class="relative h-full">
|
||||
<label for="imageFile" class="flex justify-center items-center bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600 cursor-pointer h-full">
|
||||
<div class="flex flex-col items-center">
|
||||
<div class="whitespace-nowrap">Add Image</div>
|
||||
<div class="text-xs whitespace-nowrap">(from file)</div>
|
||||
</div>
|
||||
</label>
|
||||
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/jpeg,image/png,image/gif,image/webp" required class="hidden" />
|
||||
</div>
|
||||
</div>
|
||||
<!-- Neuer Button Paste Image -->
|
||||
<div class="flex-1">
|
||||
<button (click)="pasteImage()" class="w-full bg-purple-500 text-white py-2 px-4 rounded hover:bg-purple-600 flex items-center justify-center h-full">
|
||||
<div class="flex flex-col items-center">
|
||||
<div class="whitespace-nowrap">Paste Image</div>
|
||||
<div class="text-xs whitespace-nowrap">(from clipboard)</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Loading overlay -->
|
||||
<div *ngIf="loading" class="absolute inset-0 bg-gray-800 bg-opacity-50 flex items-center justify-center z-10">
|
||||
<div class="bg-white p-4 rounded shadow">
|
||||
<p class="text-sm text-gray-700">Processing in progress...</p>
|
||||
</div>
|
||||
</div>
|
||||
<!-- CreateDeckModalComponent -->
|
||||
<app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal>
|
||||
|
||||
<!-- UploadImageModalComponent -->
|
||||
<!-- <app-upload-image-modal (imageUploaded)="onImageUploaded($event)"></app-upload-image-modal> -->
|
||||
<app-edit-image-modal *ngIf="imageData" [deckName]="activeDeck.name" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal>
|
||||
<!-- TrainingComponent -->
|
||||
<app-training *ngIf="trainingsDeck" [deck]="trainingsDeck" (close)="closeTraining()"></app-training>
|
||||
<!-- MoveImageModalComponent -->
|
||||
<app-move-image-modal *ngIf="imageToMove" [image]="imageToMove.image" [sourceDeck]="imageToMove.sourceDeck" [decks]="decks" (moveCompleted)="onImageMoved()" (closed)="imageToMove = null"> </app-move-image-modal>
|
||||
</div>
|
||||
546
src/app/deck-list.component.ts
Normal file
546
src/app/deck-list.component.ts
Normal file
@@ -0,0 +1,546 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { ChangeDetectorRef, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { CreateDeckModalComponent } from './create-deck-modal/create-deck-modal.component';
|
||||
import { EditImageModalComponent } from './edit-image-modal/edit-image-modal.component';
|
||||
import { MoveImageModalComponent } from './move-image-modal/move-image-modal.component';
|
||||
import { Box, Deck, DeckImage, DeckService, OcrResult } from './services/deck.service';
|
||||
import { PopoverService } from './services/popover.service';
|
||||
import { TrainingComponent } from './training/training.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-deck-list',
|
||||
templateUrl: './deck-list.component.html',
|
||||
standalone: true,
|
||||
styles: `
|
||||
.popover {
|
||||
padding: 1rem;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 0.5rem;
|
||||
background-color: white;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
max-width: 300px;
|
||||
}
|
||||
`,
|
||||
imports: [
|
||||
CommonModule,
|
||||
CreateDeckModalComponent,
|
||||
TrainingComponent,
|
||||
EditImageModalComponent,
|
||||
MoveImageModalComponent, // Adding the new component
|
||||
FormsModule,
|
||||
],
|
||||
})
|
||||
export class DeckListComponent implements OnInit {
|
||||
decks: Deck[] = [];
|
||||
trainingsDeck: Deck | null = null;
|
||||
activeDeck: Deck | null = null;
|
||||
loading: boolean = false;
|
||||
|
||||
@ViewChild(CreateDeckModalComponent)
|
||||
createDeckModal!: CreateDeckModalComponent;
|
||||
@ViewChild(EditImageModalComponent) editModal!: EditImageModalComponent;
|
||||
@ViewChild('imageFile') imageFileElement!: ElementRef;
|
||||
|
||||
imageData: {
|
||||
imageSrc: string | ArrayBuffer | null;
|
||||
deckImage: DeckImage;
|
||||
} | null = null;
|
||||
|
||||
// Set to track expanded decks
|
||||
expandedDecks: Set<string> = new Set<string>();
|
||||
|
||||
// State for moving images
|
||||
imageToMove: { image: DeckImage; sourceDeck: Deck } | null = null;
|
||||
|
||||
constructor(private deckService: DeckService, private cdr: ChangeDetectorRef, private http: HttpClient, private popoverService: PopoverService) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadExpandedDecks();
|
||||
this.loadDecks();
|
||||
}
|
||||
|
||||
loadDecks(): void {
|
||||
this.deckService.getDecks().subscribe({
|
||||
next: data => {
|
||||
this.decks = data;
|
||||
// Versuche, das zuvor gespeicherte aktive Deck zu laden
|
||||
const storedActiveDeckName = localStorage.getItem('activeDeckName');
|
||||
if (storedActiveDeckName) {
|
||||
const foundDeck = this.decks.find(deck => deck.name === storedActiveDeckName);
|
||||
if (foundDeck) {
|
||||
this.activeDeck = foundDeck;
|
||||
} else if (this.decks.length > 0) {
|
||||
this.activeDeck = this.decks[0];
|
||||
localStorage.setItem('activeDeckName', this.activeDeck.name);
|
||||
}
|
||||
} else if (this.decks.length > 0) {
|
||||
this.activeDeck = this.decks[0];
|
||||
localStorage.setItem('activeDeckName', this.activeDeck.name);
|
||||
} else {
|
||||
this.activeDeck = null;
|
||||
}
|
||||
},
|
||||
error: err => console.error('Error loading decks', err),
|
||||
});
|
||||
}
|
||||
|
||||
// Updated toggle method
|
||||
toggleDeckExpansion(deck: Deck): void {
|
||||
this.activeDeck = deck;
|
||||
localStorage.setItem('activeDeckName', deck.name);
|
||||
}
|
||||
|
||||
// Method to open the delete confirmation popover
|
||||
openDeletePopover(deckName: string): void {
|
||||
this.popoverService.show({
|
||||
title: 'Delete Deck',
|
||||
message: 'Are you sure you want to delete this deck?',
|
||||
confirmText: 'Delete',
|
||||
onConfirm: () => this.confirmDelete(deckName),
|
||||
});
|
||||
}
|
||||
|
||||
// Method to check if a deck is active
|
||||
isDeckActive(deck: Deck): boolean {
|
||||
return this.activeDeck?.name === deck.name;
|
||||
}
|
||||
|
||||
// Method to confirm the deletion of a deck
|
||||
confirmDelete(deckName: string): void {
|
||||
this.deckService.deleteDeck(deckName).subscribe({
|
||||
next: () => {
|
||||
this.loadDecks();
|
||||
this.activeDeck = this.decks.length > 0 ? this.decks[0] : null;
|
||||
},
|
||||
error: err => console.error('Error deleting deck', err),
|
||||
});
|
||||
}
|
||||
|
||||
// Method to open the rename popover
|
||||
openRenamePopover(deck: Deck): void {
|
||||
this.popoverService.showWithInput({
|
||||
title: 'Rename Deck',
|
||||
message: 'Enter the new name for the deck:',
|
||||
confirmText: 'Rename',
|
||||
inputValue: deck.name,
|
||||
onConfirm: (inputValue?: string) => this.confirmRename(deck, inputValue),
|
||||
});
|
||||
}
|
||||
|
||||
// Method to confirm the renaming of a deck
|
||||
confirmRename(deck: Deck, newName?: string): void {
|
||||
if (newName && newName.trim() !== '' && newName !== deck.name) {
|
||||
this.deckService.renameDeck(deck.name, newName).subscribe({
|
||||
next: () => {
|
||||
if (this.activeDeck?.name === deck.name) {
|
||||
this.activeDeck.name = newName;
|
||||
}
|
||||
this.loadDecks();
|
||||
},
|
||||
error: err => console.error('Error renaming deck', err),
|
||||
});
|
||||
} else {
|
||||
// Optional: Handle ungültigen neuen Namen
|
||||
console.warn('Invalid new deck name.');
|
||||
}
|
||||
}
|
||||
|
||||
openRenameImagePopover(image: DeckImage): void {
|
||||
this.popoverService.showWithInput({
|
||||
title: 'Rename Deck',
|
||||
message: 'Enter the new name for the deck:',
|
||||
confirmText: 'Rename',
|
||||
inputValue: image.name,
|
||||
onConfirm: (inputValue?: string) => this.confirmRenameImage(image, inputValue),
|
||||
});
|
||||
}
|
||||
// Method to confirm the renaming of a deck
|
||||
confirmRenameImage(image: DeckImage, newName?: string): void {
|
||||
if (newName && newName.trim() !== '' && newName !== image.name) {
|
||||
this.deckService.renameImage(image.bildid, newName).subscribe({
|
||||
next: () => {
|
||||
this.loadDecks();
|
||||
},
|
||||
error: err => console.error('Error renaming image', err),
|
||||
});
|
||||
} else {
|
||||
// Optional: Handle ungültigen neuen Namen
|
||||
console.warn('Invalid new image name.');
|
||||
}
|
||||
}
|
||||
// Delete-Image Methoden ersetzen
|
||||
deleteImage(deck: Deck, image: DeckImage): void {
|
||||
this.popoverService.show({
|
||||
title: 'Delete Image',
|
||||
message: `Are you sure you want to delete the image ${image.name}?`,
|
||||
confirmText: 'Delete',
|
||||
showCancel: true,
|
||||
onConfirm: () => this.confirmImageDelete(deck, image),
|
||||
});
|
||||
}
|
||||
|
||||
confirmImageDelete(deck: Deck, image: DeckImage): void {
|
||||
const imageId = image.bildid;
|
||||
|
||||
this.deckService.deleteImage(imageId).subscribe({
|
||||
next: () => {
|
||||
this.loadDecks();
|
||||
if (this.activeDeck) {
|
||||
this.activeDeck.images = this.activeDeck.images.filter(img => img.bildid !== imageId);
|
||||
this.cdr.detectChanges();
|
||||
}
|
||||
},
|
||||
error: err => console.error('Error deleting image', err),
|
||||
});
|
||||
}
|
||||
|
||||
// Method to edit an image in a deck
|
||||
editImage(deck: Deck, image: DeckImage): void {
|
||||
let imageSrc = null;
|
||||
fetch(`/images/${image.bildid}/original.webp`)
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
return response.blob();
|
||||
})
|
||||
.then(blob => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
imageSrc = reader.result; // Base64 string
|
||||
this.imageData = { imageSrc, deckImage: image };
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error loading image:', error);
|
||||
});
|
||||
}
|
||||
|
||||
// Method to open the training component
|
||||
openTraining(deck: Deck): void {
|
||||
this.trainingsDeck = deck;
|
||||
}
|
||||
|
||||
// Method to close the training component
|
||||
closeTraining(): void {
|
||||
this.trainingsDeck = null;
|
||||
this.loadDecks();
|
||||
}
|
||||
|
||||
// Method to open the create deck modal
|
||||
openCreateDeckModal(): void {
|
||||
this.createDeckModal.open();
|
||||
}
|
||||
|
||||
// Method to check if a deck is expanded
|
||||
isDeckExpanded(deckName: string): boolean {
|
||||
return this.expandedDecks.has(deckName);
|
||||
}
|
||||
|
||||
// Method to load expanded decks from sessionStorage
|
||||
loadExpandedDecks(): void {
|
||||
const stored = sessionStorage.getItem('expandedDecks');
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed: string[] = JSON.parse(stored);
|
||||
this.expandedDecks = new Set<string>(parsed);
|
||||
} catch (e) {
|
||||
console.error('Error parsing expanded decks from sessionStorage', e);
|
||||
}
|
||||
} else {
|
||||
// If no data is stored, do not expand any decks by default
|
||||
this.expandedDecks = new Set<string>();
|
||||
}
|
||||
}
|
||||
|
||||
// Method to save expanded decks to sessionStorage
|
||||
saveExpandedDecks(): void {
|
||||
const expandedArray = Array.from(this.expandedDecks);
|
||||
sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray));
|
||||
}
|
||||
|
||||
// Handler for the imageUploaded event
|
||||
onImageUploaded(imageData: any): void {
|
||||
this.imageData = imageData;
|
||||
}
|
||||
|
||||
onClosed() {
|
||||
this.imageData = null;
|
||||
}
|
||||
|
||||
async onImageSaved() {
|
||||
// Handle saving the image data, e.g., update the list of images
|
||||
this.imageData = null;
|
||||
|
||||
// Lade die Decks neu
|
||||
this.decks = await firstValueFrom(this.deckService.getDecks());
|
||||
|
||||
// Aktualisiere den activeDeck, falls dieser der aktuelle Deck ist
|
||||
if (this.activeDeck) {
|
||||
const updatedDeck = this.decks.find(deck => deck.name === this.activeDeck?.name);
|
||||
if (updatedDeck) {
|
||||
this.activeDeck = updatedDeck;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Method to open the MoveImageModal
|
||||
openMoveImageModal(deck: Deck, image: DeckImage): void {
|
||||
this.imageToMove = { image, sourceDeck: deck };
|
||||
}
|
||||
|
||||
// Handler for the moveCompleted event
|
||||
onImageMoved(): void {
|
||||
this.imageToMove = null;
|
||||
// Speichere den Namen des aktiven Decks
|
||||
const activeDeckName = this.activeDeck?.name;
|
||||
|
||||
this.deckService.getDecks().subscribe({
|
||||
next: decks => {
|
||||
this.decks = decks;
|
||||
// Aktualisiere den activeDeck mit den neuen Daten
|
||||
if (activeDeckName) {
|
||||
this.activeDeck = this.decks.find(deck => deck.name === activeDeckName) || null;
|
||||
}
|
||||
// Force change detection
|
||||
this.cdr.detectChanges();
|
||||
},
|
||||
error: err => console.error('Error loading decks', err),
|
||||
});
|
||||
}
|
||||
|
||||
onFileChange(event: any): void {
|
||||
const file: File = event.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
// Erlaubte Dateitypen
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
|
||||
|
||||
// Prüfe den Dateityp
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
this.popoverService.show({
|
||||
title: 'Information',
|
||||
message: 'Only JPG, PNG, GIF and WebP images are allowed',
|
||||
});
|
||||
this.resetFileInput();
|
||||
return;
|
||||
}
|
||||
|
||||
// Prüfe die Dateigröße (5MB = 5 * 1024 * 1024 Bytes)
|
||||
const maxSize = 5 * 1024 * 1024; // 5MB in Bytes
|
||||
if (file.size > maxSize) {
|
||||
this.popoverService.show({
|
||||
title: 'Information',
|
||||
message: 'Image file size must not exceed 5MB',
|
||||
});
|
||||
this.resetFileInput();
|
||||
return;
|
||||
}
|
||||
|
||||
const fileNameElement = document.getElementById('fileName');
|
||||
if (fileNameElement) {
|
||||
fileNameElement.textContent = file.name;
|
||||
}
|
||||
|
||||
this.loading = true;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = async e => {
|
||||
const imageSrc = e.target?.result;
|
||||
|
||||
// Image as Base64 string without prefix (data:image/...)
|
||||
const imageBase64 = (imageSrc as string).split(',')[1];
|
||||
|
||||
try {
|
||||
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
|
||||
|
||||
if (!response || !response.results) {
|
||||
this.loading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.loading = false;
|
||||
|
||||
// Emit event with image data and OCR results
|
||||
const imageName = file?.name ?? '';
|
||||
const imageId = response.results.length > 0 ? response.results[0].name : null;
|
||||
const boxes: Box[] = [];
|
||||
response.results.forEach((result: OcrResult) => {
|
||||
const box = result.box;
|
||||
|
||||
const xs = box.map((point: number[]) => point[0]);
|
||||
const ys = box.map((point: number[]) => point[1]);
|
||||
const xMin = Math.min(...xs);
|
||||
const xMax = Math.max(...xs);
|
||||
const yMin = Math.min(...ys);
|
||||
const yMax = Math.max(...ys);
|
||||
boxes.push({ x1: xMin, x2: xMax, y1: yMin, y2: yMax, inserted: null, updated: null });
|
||||
});
|
||||
const deckImage: DeckImage = { name: imageName, bildid: imageId, boxes };
|
||||
this.imageData = { imageSrc, deckImage };
|
||||
|
||||
this.resetFileInput();
|
||||
} catch (error) {
|
||||
console.error('Error with OCR service:', error);
|
||||
this.loading = false;
|
||||
}
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the file input field so the same file can be selected again.
|
||||
*/
|
||||
resetFileInput(): void {
|
||||
if (this.imageFileElement && this.imageFileElement.nativeElement) {
|
||||
this.imageFileElement.nativeElement.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Liest das aktuelle Bild aus der Zwischenablage und setzt imageData, sodass die Edit-Image-Komponente
|
||||
* mit dem eingefügten Bild startet.
|
||||
*/
|
||||
pasteImage(): void {
|
||||
if (!navigator.clipboard || !navigator.clipboard.read) {
|
||||
this.popoverService.show({
|
||||
title: 'Fehler',
|
||||
message: 'Das Clipboard-API wird in diesem Browser nicht unterstützt.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.clipboard
|
||||
.read()
|
||||
.then(items => {
|
||||
// Suche im Clipboard nach einem Element, das ein Bild enthält
|
||||
for (const item of items) {
|
||||
for (const type of item.types) {
|
||||
if (type.startsWith('image/')) {
|
||||
// Hole den Blob des Bildes
|
||||
item.getType(type).then(blob => {
|
||||
const reader = new FileReader();
|
||||
this.loading = true;
|
||||
reader.onload = async e => {
|
||||
const imageSrc = e.target?.result;
|
||||
// Extrahiere den Base64-String (ähnlich wie in onFileChange)
|
||||
const imageBase64 = (imageSrc as string).split(',')[1];
|
||||
|
||||
try {
|
||||
// Optional: OCR-Request wie im File-Upload
|
||||
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
|
||||
let deckImage: DeckImage;
|
||||
if (response && response.results) {
|
||||
const boxes: Box[] = [];
|
||||
response.results.forEach((result: OcrResult) => {
|
||||
const box = result.box;
|
||||
const xs = box.map((point: number[]) => point[0]);
|
||||
const ys = box.map((point: number[]) => point[1]);
|
||||
const xMin = Math.min(...xs);
|
||||
const xMax = Math.max(...xs);
|
||||
const yMin = Math.min(...ys);
|
||||
const yMax = Math.max(...ys);
|
||||
boxes.push({ x1: xMin, x2: xMax, y1: yMin, y2: yMax, inserted: null, updated: null });
|
||||
});
|
||||
deckImage = {
|
||||
name: 'Pasted Image',
|
||||
bildid: response.results.length > 0 ? response.results[0].name : null,
|
||||
boxes,
|
||||
};
|
||||
} else {
|
||||
// Falls kein OCR-Ergebnis vorliegt, lege leere Boxen an
|
||||
deckImage = {
|
||||
name: 'Pasted Image',
|
||||
bildid: null,
|
||||
boxes: [],
|
||||
};
|
||||
}
|
||||
// Setze imageData – dadurch wird in der Template der <app-edit-image-modal> eingeblendet
|
||||
this.imageData = { imageSrc, deckImage };
|
||||
} catch (error) {
|
||||
console.error('Error with OCR service:', error);
|
||||
this.popoverService.show({
|
||||
title: 'Error',
|
||||
message: 'Error with OCR service.',
|
||||
});
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
return; // Beende die Schleife, sobald ein Bild gefunden wurde.
|
||||
}
|
||||
}
|
||||
}
|
||||
// Falls kein Bild gefunden wurde:
|
||||
this.popoverService.show({
|
||||
title: 'Information',
|
||||
message: 'Keine Bilddaten im Clipboard gefunden.',
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Fehler beim Zugriff auf das Clipboard:', err);
|
||||
this.popoverService.show({
|
||||
title: 'Fehler',
|
||||
message: 'Fehler beim Zugriff auf das Clipboard.',
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Methode zur Berechnung des nächsten Trainingsdatums
|
||||
getNextTrainingDate(deck: Deck): number {
|
||||
const today = this.getTodayInDays();
|
||||
const dueDates = deck.images.flatMap(image => image.boxes.map(box => (box.due ? box.due : null)));
|
||||
if (dueDates.includes(null)) {
|
||||
return today;
|
||||
}
|
||||
//const futureDueDates = dueDates.filter(date => date && date >= now);
|
||||
if (dueDates.length > 0) {
|
||||
const nextDate = dueDates.reduce((a, b) => (a < b ? a : b));
|
||||
return nextDate;
|
||||
}
|
||||
return today;
|
||||
}
|
||||
getNextTrainingString(deck: Deck): string {
|
||||
return this.daysSinceEpochToLocalDateString(this.getNextTrainingDate(deck));
|
||||
}
|
||||
// In deiner Component TypeScript Datei
|
||||
isToday(epochDays: number): boolean {
|
||||
return this.getTodayInDays() - epochDays === 0;
|
||||
}
|
||||
isBeforeToday(epochDays: number): boolean {
|
||||
return this.getTodayInDays() - epochDays > 0;
|
||||
}
|
||||
// Methode zur Berechnung der Anzahl der zu bearbeitenden Wörter
|
||||
getWordsToReview(deck: Deck): number {
|
||||
// const nextTraining = this.getNextTrainingDate(deck);
|
||||
// return deck.images.flatMap(image => image.boxes.filter(box => (box.due && new Date(box.due * 86400000) <= new Date(nextTraining)) || !box.due)).length;
|
||||
const today = this.getTodayInDays();
|
||||
return deck.images.flatMap(image => image.boxes.filter(box => (box.due && box.due <= today) || !box.due)).length;
|
||||
// this.currentImageData.boxes.filter(box => box.due === undefined || box.due <= today);
|
||||
}
|
||||
getTodayInDays(): number {
|
||||
const epoch = new Date(1970, 0, 1); // Anki uses UNIX epoch
|
||||
const today = new Date();
|
||||
return Math.floor((today.getTime() - epoch.getTime()) / (1000 * 60 * 60 * 24));
|
||||
}
|
||||
daysSinceEpochToLocalDateString(days: number): string {
|
||||
const msPerDay = 24 * 60 * 60 * 1000;
|
||||
// Erstelle ein Datum, das den exakten UTC-Zeitpunkt (Mitternacht UTC) repräsentiert:
|
||||
const utcDate = new Date(days * msPerDay);
|
||||
|
||||
// Formatiere das Datum: Mit timeZone: 'UTC' wird der UTC-Wert genutzt,
|
||||
// aber das Ausgabeformat (z. B. "4.2.2025" oder "2/4/2025") richtet sich nach der Locale.
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
timeZone: 'UTC',
|
||||
day: 'numeric',
|
||||
month: 'numeric',
|
||||
year: 'numeric',
|
||||
}).format(utcDate);
|
||||
}
|
||||
}
|
||||
42
src/app/edit-image-modal/edit-image-modal.component.html
Normal file
42
src/app/edit-image-modal/edit-image-modal.component.html
Normal file
@@ -0,0 +1,42 @@
|
||||
<div
|
||||
#editImageModal
|
||||
id="editImageModal"
|
||||
data-modal-backdrop="static"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-modal md:h-full"
|
||||
>
|
||||
<div class="relative h-full contents">
|
||||
<div class="relative bg-white rounded-lg shadow p-[20px]">
|
||||
<!-- Header with box count -->
|
||||
<div class="flex items-center justify-between px-4 pb-4 border-b rounded-t dark:border-gray-600 border-gray-200">
|
||||
<h3 class="text-xl font-semibold text-gray-900 dark:text-white">
|
||||
Edit Image <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'es' : '' }})</span>
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white"
|
||||
(click)="closeModal()"
|
||||
>
|
||||
<svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
|
||||
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
|
||||
</svg>
|
||||
<span class="sr-only">Close modal</span>
|
||||
</button>
|
||||
</div>
|
||||
<!-- Canvas -->
|
||||
<div class="p-4 md:p-5 space-y-4">
|
||||
<div class="mt-4">
|
||||
<canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Buttons below the canvas -->
|
||||
<div class="mt-4 flex justify-between">
|
||||
<button (click)="save()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">Save</button>
|
||||
<button (click)="addNewBox()" class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">New Box</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- </div> -->
|
||||
</div>
|
||||
</div>
|
||||
280
src/app/edit-image-modal/edit-image-modal.component.ts
Normal file
280
src/app/edit-image-modal/edit-image-modal.component.ts
Normal file
@@ -0,0 +1,280 @@
|
||||
// src/app/edit-image-modal.component.ts
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnDestroy, Output, ViewChild } from '@angular/core';
|
||||
import { fabric } from 'fabric';
|
||||
import { Modal } from 'flowbite';
|
||||
import { DeckImage, DeckService } from '../services/deck.service';
|
||||
import { PopoverService } from '../services/popover.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-edit-image-modal',
|
||||
templateUrl: './edit-image-modal.component.html',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
})
|
||||
export class EditImageModalComponent implements AfterViewInit, OnDestroy {
|
||||
// Constant for box color
|
||||
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Red with transparency
|
||||
|
||||
@Input() deckName: string = '';
|
||||
@Input() imageData: { imageSrc: string | ArrayBuffer | null; deckImage: DeckImage | null } = { imageSrc: null, deckImage: null };
|
||||
@Output() imageSaved = new EventEmitter<void>();
|
||||
@Output() closed = new EventEmitter<void>();
|
||||
@ViewChild('editImageModal') modalElement!: ElementRef;
|
||||
@ViewChild('canvas') canvasElement!: ElementRef<HTMLCanvasElement>;
|
||||
|
||||
detectedText: string = '';
|
||||
boxes: { x1: number; x2: number; y1: number; y2: number; id: number; inserted: string; updated: string }[] = [];
|
||||
canvas!: fabric.Canvas;
|
||||
|
||||
maxCanvasWidth: number = 0;
|
||||
maxCanvasHeight: number = 0;
|
||||
|
||||
private keyDownHandler!: (e: KeyboardEvent) => void;
|
||||
modal: any;
|
||||
|
||||
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
|
||||
|
||||
async ngAfterViewInit() {
|
||||
this.modal = new Modal(this.modalElement.nativeElement, {
|
||||
backdrop: 'static',
|
||||
onHide: () => {
|
||||
this.closed.emit();
|
||||
},
|
||||
});
|
||||
|
||||
this.maxCanvasWidth = window.innerWidth * 0.6;
|
||||
this.maxCanvasHeight = window.innerHeight * 0.6;
|
||||
|
||||
this.keyDownHandler = this.onKeyDown.bind(this);
|
||||
document.addEventListener('keydown', this.keyDownHandler);
|
||||
|
||||
await this.initializeCanvas();
|
||||
|
||||
this.modal.show();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
document.removeEventListener('keydown', this.keyDownHandler);
|
||||
if (this.canvas) {
|
||||
this.canvas.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.modal.show();
|
||||
}
|
||||
|
||||
closeModal(): void {
|
||||
this.modal.hide();
|
||||
}
|
||||
|
||||
async initializeCanvas() {
|
||||
await this.processImage();
|
||||
}
|
||||
|
||||
private loadFabricImage(url: string): Promise<fabric.Image> {
|
||||
return new Promise((resolve, reject) => {
|
||||
fabric.Image.fromURL(
|
||||
url,
|
||||
img => {
|
||||
resolve(img);
|
||||
},
|
||||
{
|
||||
crossOrigin: 'anonymous',
|
||||
originX: 'left',
|
||||
originY: 'top',
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async processImage(): Promise<void> {
|
||||
try {
|
||||
if (!this.imageData) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.canvas = new fabric.Canvas(this.canvasElement.nativeElement);
|
||||
|
||||
// Set background image
|
||||
const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string);
|
||||
|
||||
const originalWidth = backgroundImage.width!;
|
||||
const originalHeight = backgroundImage.height!;
|
||||
|
||||
const scaleX = this.maxCanvasWidth / originalWidth;
|
||||
const scaleY = this.maxCanvasHeight / originalHeight;
|
||||
const scaleFactor = Math.min(scaleX, scaleY, 1);
|
||||
|
||||
const canvasWidth = originalWidth * scaleFactor;
|
||||
const canvasHeight = originalHeight * scaleFactor;
|
||||
|
||||
this.canvas.setWidth(canvasWidth);
|
||||
this.canvas.setHeight(canvasHeight);
|
||||
|
||||
backgroundImage.set({
|
||||
scaleX: scaleFactor,
|
||||
scaleY: scaleFactor,
|
||||
});
|
||||
|
||||
this.canvas.setBackgroundImage(backgroundImage, this.canvas.renderAll.bind(this.canvas));
|
||||
|
||||
this.boxes = [];
|
||||
|
||||
// Add boxes
|
||||
this.imageData.deckImage?.boxes.forEach(box => {
|
||||
const rect = new fabric.Rect({
|
||||
left: box.x1 * scaleFactor,
|
||||
top: box.y1 * scaleFactor,
|
||||
width: (box.x2 - box.x1) * scaleFactor,
|
||||
height: (box.y2 - box.y1) * scaleFactor,
|
||||
fill: this.BOX_COLOR, // Use the constant
|
||||
selectable: true,
|
||||
hasControls: true,
|
||||
hasBorders: true,
|
||||
objectCaching: false,
|
||||
data: { id: box.id, inserted: box.inserted, updated: box.updated },
|
||||
});
|
||||
|
||||
rect.on('modified', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('moved', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('scaled', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('rotated', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('removed', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
|
||||
this.canvas.add(rect);
|
||||
});
|
||||
|
||||
this.updateBoxCoordinates();
|
||||
// this.detectedText = ocrResults.map(result => result.text).join('\n');
|
||||
} catch (error) {
|
||||
console.error('Error processing image:', error);
|
||||
}
|
||||
}
|
||||
|
||||
onKeyDown(e: KeyboardEvent): void {
|
||||
if (e.key === 'Delete' || e.key === 'Del') {
|
||||
const activeObject = this.canvas.getActiveObject();
|
||||
if (activeObject) {
|
||||
this.canvas.remove(activeObject);
|
||||
this.canvas.requestRenderAll();
|
||||
this.updateBoxCoordinates();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateBoxCoordinates(): void {
|
||||
this.boxes = [];
|
||||
|
||||
let scaleFactor = 1;
|
||||
const bgImage = this.canvas.backgroundImage;
|
||||
if (bgImage && bgImage instanceof fabric.Image) {
|
||||
scaleFactor = bgImage.get('scaleX') || 1;
|
||||
}
|
||||
|
||||
this.canvas.getObjects('rect').forEach((rect: fabric.Rect) => {
|
||||
const left = rect.left!;
|
||||
const top = rect.top!;
|
||||
const width = rect.width! * rect.scaleX!;
|
||||
const height = rect.height! * rect.scaleY!;
|
||||
|
||||
const x1 = left / scaleFactor;
|
||||
const y1 = top / scaleFactor;
|
||||
const x2 = (left + width) / scaleFactor;
|
||||
const y2 = (top + height) / scaleFactor;
|
||||
|
||||
this.boxes.push({
|
||||
x1: Math.round(x1),
|
||||
x2: Math.round(x2),
|
||||
y1: Math.round(y1),
|
||||
y2: Math.round(y2),
|
||||
id: rect.data?.id,
|
||||
inserted: rect.data?.inserted,
|
||||
updated: rect.data?.updated,
|
||||
});
|
||||
});
|
||||
|
||||
this.canvas.requestRenderAll();
|
||||
}
|
||||
|
||||
addNewBox(): void {
|
||||
if (!this.canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
const boxWidth = 100;
|
||||
const boxHeight = 50;
|
||||
|
||||
const canvasWidth = this.canvas.getWidth();
|
||||
const canvasHeight = this.canvas.getHeight();
|
||||
|
||||
const rect = new fabric.Rect({
|
||||
left: (canvasWidth - boxWidth) / 2,
|
||||
top: (canvasHeight - boxHeight) / 2,
|
||||
width: boxWidth,
|
||||
height: boxHeight,
|
||||
fill: this.BOX_COLOR, // Use the constant
|
||||
selectable: true,
|
||||
hasControls: true,
|
||||
hasBorders: true,
|
||||
objectCaching: false,
|
||||
});
|
||||
rect.on('modified', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('moved', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('scaled', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('rotated', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
rect.on('removed', () => {
|
||||
this.updateBoxCoordinates();
|
||||
});
|
||||
|
||||
this.canvas.add(rect);
|
||||
this.canvas.setActiveObject(rect);
|
||||
this.canvas.requestRenderAll();
|
||||
|
||||
this.updateBoxCoordinates();
|
||||
}
|
||||
|
||||
save(): void {
|
||||
// Implement the logic to save the image data here
|
||||
// For example, via a service or directly here
|
||||
const data = {
|
||||
deckname: this.deckName,
|
||||
bildname: this.imageData.deckImage?.name, // this.imageFile?.name,
|
||||
bildid: this.imageData.deckImage?.bildid,
|
||||
boxes: this.boxes,
|
||||
};
|
||||
this.deckService.saveImageData(data).subscribe({
|
||||
next: () => {
|
||||
this.imageSaved.emit();
|
||||
this.closeModal();
|
||||
},
|
||||
error: err => {
|
||||
console.error('Error saving image:', err);
|
||||
this.popoverService.show({
|
||||
title: 'Error',
|
||||
message: 'Error saving image.',
|
||||
});
|
||||
this.closeModal();
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
12
src/app/environments/environment.prod.ts
Normal file
12
src/app/environments/environment.prod.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export const environment = {
|
||||
production: true,
|
||||
firebase: {
|
||||
apiKey: 'AIzaSyBBH7mGJtwY-6_x0kCmyWCGe6JCesRS49k',
|
||||
authDomain: 'haiki-452bd.firebaseapp.com',
|
||||
projectId: 'haiki-452bd',
|
||||
storageBucket: 'haiki-452bd.firebasestorage.app',
|
||||
messagingSenderId: '263288723576',
|
||||
appId: '1:263288723576:web:2bc87146ef52d276f5358d',
|
||||
measurementId: 'G-C1C3N16KB3',
|
||||
},
|
||||
};
|
||||
12
src/app/environments/environment.ts
Normal file
12
src/app/environments/environment.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export const environment = {
|
||||
production: false,
|
||||
firebase: {
|
||||
apiKey: 'AIzaSyBBH7mGJtwY-6_x0kCmyWCGe6JCesRS49k',
|
||||
authDomain: 'haiki-452bd.firebaseapp.com',
|
||||
projectId: 'haiki-452bd',
|
||||
storageBucket: 'haiki-452bd.firebasestorage.app',
|
||||
messagingSenderId: '263288723576',
|
||||
appId: '1:263288723576:web:2bc87146ef52d276f5358d',
|
||||
measurementId: 'G-C1C3N16KB3',
|
||||
},
|
||||
};
|
||||
22
src/app/move-image-modal/move-image-modal.component.html
Normal file
22
src/app/move-image-modal/move-image-modal.component.html
Normal file
@@ -0,0 +1,22 @@
|
||||
<div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
|
||||
<div class="bg-white rounded-lg shadow-lg w-96 p-6">
|
||||
<h2 class="text-xl font-semibold mb-4">Move Image</h2>
|
||||
<p class="mb-4">Select the target deck for the image <strong>{{ image.name }}</strong>.</p>
|
||||
<select [(ngModel)]="selectedDeckId" class="w-full p-2 border border-gray-300 rounded mb-4">
|
||||
<option *ngFor="let deck of decks" [value]="deck.name" [disabled]="deck.name === sourceDeck.name">
|
||||
{{ deck.name }}
|
||||
</option>
|
||||
</select>
|
||||
<div class="flex justify-end space-x-2">
|
||||
<button (click)="close()" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600">
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
(click)="moveImage()"
|
||||
[disabled]="!selectedDeckId"
|
||||
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
|
||||
Move
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
47
src/app/move-image-modal/move-image-modal.component.ts
Normal file
47
src/app/move-image-modal/move-image-modal.component.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, EventEmitter, Input, Output } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Deck, DeckImage, DeckService } from '../services/deck.service';
|
||||
import { PopoverService } from '../services/popover.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-move-image-modal',
|
||||
templateUrl: './move-image-modal.component.html',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule],
|
||||
})
|
||||
export class MoveImageModalComponent {
|
||||
@Input() image!: DeckImage;
|
||||
@Input() sourceDeck!: Deck;
|
||||
@Input() decks: Deck[] = [];
|
||||
@Output() moveCompleted = new EventEmitter<void>();
|
||||
@Output() closed = new EventEmitter<void>();
|
||||
|
||||
selectedDeckId: number | null = null;
|
||||
|
||||
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
|
||||
|
||||
moveImage(): void {
|
||||
if (this.selectedDeckId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.deckService.moveImage(this.image.bildid, this.selectedDeckId).subscribe({
|
||||
next: () => {
|
||||
this.moveCompleted.emit();
|
||||
this.close();
|
||||
},
|
||||
error: err => {
|
||||
console.error('Error moving image:', err);
|
||||
this.popoverService.show({
|
||||
title: 'Error',
|
||||
message: 'Error moving image.',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed.emit();
|
||||
}
|
||||
}
|
||||
73
src/app/service/auth.interceptor.ts
Normal file
73
src/app/service/auth.interceptor.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { HttpInterceptorFn } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Auth } from '@angular/fire/auth';
|
||||
import { from } from 'rxjs';
|
||||
import { catchError, switchMap } from 'rxjs/operators';
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
const auth = inject(Auth); // Injizieren Sie den Auth-Dienst
|
||||
const token = localStorage.getItem('accessToken');
|
||||
|
||||
if (token) {
|
||||
const decodedToken = decodeToken(token);
|
||||
const expirationTime = decodedToken.exp * 1000; // Umwandeln in Millisekunden
|
||||
const currentTime = Date.now();
|
||||
|
||||
if (currentTime > expirationTime) {
|
||||
// Token ist abgelaufen, erneuern Sie es
|
||||
return from(refreshToken(auth)).pipe(
|
||||
switchMap(newToken => {
|
||||
const clonedReq = req.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${newToken}`,
|
||||
},
|
||||
});
|
||||
return next(clonedReq);
|
||||
}),
|
||||
catchError(error => {
|
||||
console.error('Failed to refresh token', error);
|
||||
return next(req); // Ohne Token fortfahren
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
// Token ist gültig
|
||||
const clonedReq = req.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
return next(clonedReq);
|
||||
}
|
||||
} else {
|
||||
return next(req);
|
||||
}
|
||||
};
|
||||
|
||||
async function refreshToken(auth: Auth): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const unsubscribe = auth.onAuthStateChanged(async user => {
|
||||
if (user) {
|
||||
try {
|
||||
const newToken = await user.getIdToken(true); // Token erneuern
|
||||
localStorage.setItem('accessToken', newToken);
|
||||
resolve(newToken);
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh token', error);
|
||||
reject(error);
|
||||
}
|
||||
} else {
|
||||
reject(new Error('No authenticated user found'));
|
||||
}
|
||||
unsubscribe(); // Abonnement beenden
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function decodeToken(token: string): any {
|
||||
try {
|
||||
return JSON.parse(atob(token.split('.')[1]));
|
||||
} catch (e) {
|
||||
console.error('Error decoding token', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
19
src/app/service/click-outside.directive.ts
Normal file
19
src/app/service/click-outside.directive.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Directive, ElementRef, EventEmitter, HostListener, Output } from '@angular/core';
|
||||
|
||||
@Directive({
|
||||
selector: '[appClickOutside]',
|
||||
standalone: true,
|
||||
})
|
||||
export class ClickOutsideDirective {
|
||||
@Output() clickOutside = new EventEmitter<void>();
|
||||
|
||||
constructor(private elementRef: ElementRef) {}
|
||||
|
||||
@HostListener('document:click', ['$event.target'])
|
||||
onClick(target: HTMLElement) {
|
||||
const clickedInside = this.elementRef.nativeElement.contains(target);
|
||||
if (!clickedInside) {
|
||||
this.clickOutside.emit();
|
||||
}
|
||||
}
|
||||
}
|
||||
140
src/app/services/deck.service.ts
Normal file
140
src/app/services/deck.service.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { map, Observable } from 'rxjs';
|
||||
|
||||
export interface Deck {
|
||||
name: string;
|
||||
images: DeckImage[];
|
||||
}
|
||||
|
||||
export interface DeckImage {
|
||||
boxes: Box[];
|
||||
name: string;
|
||||
bildid: string;
|
||||
}
|
||||
|
||||
export interface Box {
|
||||
id?: number;
|
||||
x1: number;
|
||||
x2: number;
|
||||
y1: number;
|
||||
y2: number;
|
||||
due?: number;
|
||||
ivl?: number;
|
||||
factor?: number;
|
||||
reps?: number;
|
||||
lapses?: number;
|
||||
isGraduated?: boolean;
|
||||
inserted: string;
|
||||
updated: string;
|
||||
}
|
||||
|
||||
export interface BackendBox {
|
||||
bildname: string;
|
||||
deckid: number;
|
||||
id: number;
|
||||
x1: number;
|
||||
x2: number;
|
||||
y1: number;
|
||||
y2: number;
|
||||
}
|
||||
|
||||
// Defines a single point pair [x, y]
|
||||
type OcrPoint = [number, number];
|
||||
|
||||
// Defines the box as an array of four points
|
||||
type OcrBox = [OcrPoint, OcrPoint, OcrPoint, OcrPoint];
|
||||
|
||||
// Interface for each JSON object
|
||||
export interface OcrResult {
|
||||
box: OcrBox;
|
||||
confidence: number;
|
||||
name: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class DeckService {
|
||||
private apiUrl = '/api/decks';
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
getDecks(): Observable<Deck[]> {
|
||||
return this.http.get<any[]>(this.apiUrl).pipe(
|
||||
map(decks =>
|
||||
decks.map(deck => ({
|
||||
name: deck.name,
|
||||
images: this.groupImagesByName(deck.images),
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private groupImagesByName(images: any[]): DeckImage[] {
|
||||
const imageMap: { [key: string]: DeckImage } = {};
|
||||
|
||||
images.forEach(image => {
|
||||
if (!imageMap[image.bildid]) {
|
||||
imageMap[image.bildid] = {
|
||||
name: image.name,
|
||||
bildid: image.bildid,
|
||||
boxes: [],
|
||||
};
|
||||
}
|
||||
imageMap[image.bildid].boxes.push({
|
||||
id: image.id,
|
||||
x1: image.x1,
|
||||
x2: image.x2,
|
||||
y1: image.y1,
|
||||
y2: image.y2,
|
||||
due: image.due,
|
||||
ivl: image.ivl,
|
||||
factor: image.factor,
|
||||
reps: image.reps,
|
||||
lapses: image.lapses,
|
||||
isGraduated: image.isGraduated ? true : false,
|
||||
inserted: image.inserted,
|
||||
updated: image.updated,
|
||||
});
|
||||
});
|
||||
|
||||
return Object.values(imageMap);
|
||||
}
|
||||
|
||||
getDeck(deckname: string): Observable<Deck> {
|
||||
return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`);
|
||||
}
|
||||
|
||||
createDeck(deckname: string): Observable<any> {
|
||||
return this.http.post(this.apiUrl, { deckname });
|
||||
}
|
||||
|
||||
deleteDeck(deckName: string): Observable<any> {
|
||||
return this.http.delete(`${this.apiUrl}/${encodeURIComponent(deckName)}`);
|
||||
}
|
||||
renameDeck(oldDeckName: string, newDeckName: string): Observable<any> {
|
||||
return this.http.put(`${this.apiUrl}/${encodeURIComponent(oldDeckName)}/rename`, { newDeckName });
|
||||
}
|
||||
renameImage(bildid: string, newImageName: string): Observable<any> {
|
||||
return this.http.put(`${this.apiUrl}/image/${encodeURIComponent(bildid)}/rename`, { newImageName });
|
||||
}
|
||||
saveImageData(data: any): Observable<any> {
|
||||
return this.http.post(`${this.apiUrl}/image`, data);
|
||||
}
|
||||
|
||||
// New method to delete an image
|
||||
deleteImage(imageName: string): Observable<any> {
|
||||
return this.http.delete(`${this.apiUrl}/image/${imageName}`);
|
||||
}
|
||||
|
||||
// New method to move an image
|
||||
moveImage(imageId: string, targetDeckId: number): Observable<any> {
|
||||
return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId });
|
||||
}
|
||||
|
||||
updateBox(box: Box): Observable<any> {
|
||||
return this.http.put(`${this.apiUrl}/boxes/${box.id}`, box);
|
||||
}
|
||||
}
|
||||
38
src/app/services/popover.service.ts
Normal file
38
src/app/services/popover.service.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
// popover.service.ts
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Subject } from 'rxjs';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PopoverService {
|
||||
private showPopoverSource = new Subject<{
|
||||
title: string;
|
||||
message: string;
|
||||
showInput: boolean;
|
||||
showCancel: boolean;
|
||||
inputValue: string;
|
||||
confirmText: string;
|
||||
|
||||
onConfirm: () => void;
|
||||
onCancel?: () => void;
|
||||
}>();
|
||||
|
||||
popoverState$ = this.showPopoverSource.asObservable();
|
||||
|
||||
show(options: { title: string; message: string; confirmText?: string; showCancel?: boolean; onConfirm?: (inputValue?: string) => void; onCancel?: () => void }) {
|
||||
this.showPopoverSource.next({
|
||||
showInput: false,
|
||||
inputValue: null,
|
||||
confirmText: 'Ok',
|
||||
showCancel: false,
|
||||
onConfirm: (inputValue?: string) => {},
|
||||
...options,
|
||||
});
|
||||
}
|
||||
showWithInput(options: { title: string; message: string; confirmText: string; inputValue: string; onConfirm: (inputValue?: string) => void; onCancel?: () => void }) {
|
||||
this.showPopoverSource.next({
|
||||
showInput: true,
|
||||
showCancel: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
}
|
||||
26
src/app/services/user.service.ts
Normal file
26
src/app/services/user.service.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
|
||||
export interface User {
|
||||
name: string;
|
||||
email: string;
|
||||
sign_in_provider: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class UserService {
|
||||
// Passe die URL an, je nachdem wie dein Backend-Routing definiert ist.
|
||||
private apiUrl = '/api/users';
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
/**
|
||||
* Sendet die Benutzerinformationen an das Backend.
|
||||
*/
|
||||
logIn(user: User): Promise<any> {
|
||||
return lastValueFrom(this.http.post<any>(this.apiUrl, user));
|
||||
}
|
||||
}
|
||||
33
src/app/training/training.component.html
Normal file
33
src/app/training/training.component.html
Normal file
@@ -0,0 +1,33 @@
|
||||
<div class="mt-10 mx-auto max-w-5xl">
|
||||
<h2 class="text-2xl font-bold mb-4">Training: {{ deck.name }}</h2>
|
||||
<div class="rounded-lg p-6 flex flex-col items-center">
|
||||
<canvas #canvas class="mb-4 border max-h-[50vh]"></canvas>
|
||||
|
||||
<div class="flex space-x-4 mb-4">
|
||||
<!-- Show Button -->
|
||||
<button (click)="showText()" class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600" [disabled]="isShowingBox || currentBoxIndex >= boxesToReview.length">Show</button>
|
||||
|
||||
<!-- Again Button -->
|
||||
<button (click)="markAgain()" class="bg-orange-500 disabled:bg-orange-200 text-white py-2 px-4 rounded hover:bg-orange-600" [disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length">
|
||||
Again ({{ getNextInterval(currentBox, 'again') }})
|
||||
</button>
|
||||
|
||||
<!-- Good Button -->
|
||||
<button (click)="markGood()" class="bg-blue-500 disabled:bg-blue-200 text-white py-2 px-4 rounded hover:bg-blue-600" [disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length">
|
||||
Good ({{ getNextInterval(currentBox, 'good') }})
|
||||
</button>
|
||||
|
||||
<!-- Easy Button -->
|
||||
<button (click)="markEasy()" class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600" [disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length">
|
||||
Easy ({{ getNextInterval(currentBox, 'easy') }})
|
||||
</button>
|
||||
|
||||
<!-- Next Image Button -->
|
||||
<button (click)="skipToNextImage()" class="bg-yellow-500 disabled:bg-yellow-200 text-white py-2 px-4 rounded hover:bg-yellow-600" [disabled]="currentImageIndex >= deck.images.length">Next Image</button>
|
||||
</div>
|
||||
|
||||
<p class="mt-2">{{ progress }}</p>
|
||||
|
||||
<button (click)="closeTraining()" class="mt-4 text-gray-500 hover:text-gray-700 underline">End Training</button>
|
||||
</div>
|
||||
</div>
|
||||
459
src/app/training/training.component.ts
Normal file
459
src/app/training/training.component.ts
Normal file
@@ -0,0 +1,459 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
import { Box, Deck, DeckImage, DeckService } from '../services/deck.service';
|
||||
import { PopoverService } from '../services/popover.service';
|
||||
|
||||
const LEARNING_STEPS = {
|
||||
AGAIN: 1, // 1 minute
|
||||
GOOD: 10, // 10 minutes
|
||||
GRADUATION: 1440, // 1 day (in minutes)
|
||||
};
|
||||
|
||||
const FACTOR_CHANGES = {
|
||||
AGAIN: 0.85, // Reduce factor by 15%
|
||||
EASY: 1.15, // Increase factor by 15%
|
||||
MIN: 1.3, // Minimum factor allowed
|
||||
MAX: 2.9, // Maximum factor allowed
|
||||
};
|
||||
const EASY_INTERVAL = 4 * 1440; // 4 days in minutes
|
||||
@Component({
|
||||
selector: 'app-training',
|
||||
templateUrl: './training.component.html',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
})
|
||||
export class TrainingComponent implements OnInit {
|
||||
@Input() deck!: Deck;
|
||||
@Output() close = new EventEmitter<void>();
|
||||
|
||||
@ViewChild('canvas', { static: false }) canvasRef!: ElementRef<HTMLCanvasElement>;
|
||||
|
||||
currentImageIndex: number = 0;
|
||||
currentImageData: DeckImage | null = null;
|
||||
currentBoxIndex: number = 0;
|
||||
boxesToReview: Box[] = [];
|
||||
boxRevealed: boolean[] = [];
|
||||
|
||||
isShowingBox: boolean = false;
|
||||
isTrainingFinished: boolean = false;
|
||||
|
||||
constructor(private deckService: DeckService, private popoverService: PopoverService) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
// Initialization was done in ngAfterViewInit
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
// Initialize the first image and its boxes
|
||||
if (this.deck && this.deck.images.length > 0) {
|
||||
this.loadImage(this.currentImageIndex);
|
||||
} else {
|
||||
this.popoverService.show({
|
||||
title: 'Information',
|
||||
message: 'No deck or images available.',
|
||||
});
|
||||
this.close.emit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the image based on the given index and initializes the boxes to review.
|
||||
* @param imageIndex Index of the image to load in the deck
|
||||
*/
|
||||
loadImage(imageIndex: number): void {
|
||||
if (imageIndex >= this.deck.images.length) {
|
||||
this.endTraining();
|
||||
return;
|
||||
}
|
||||
|
||||
this.currentImageData = this.deck.images[imageIndex];
|
||||
// Initialize the boxes for the current round
|
||||
this.initializeBoxesToReview();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines all due boxes for the current round, shuffles them, and resets the current box index.
|
||||
* If no boxes are left to review, it moves to the next image.
|
||||
*/
|
||||
initializeBoxesToReview(): void {
|
||||
if (!this.currentImageData) {
|
||||
this.nextImage();
|
||||
return;
|
||||
}
|
||||
|
||||
// Filter all boxes that are due (due <= today)
|
||||
const today = this.getTodayInDays();
|
||||
this.boxesToReview = this.currentImageData.boxes.filter(box => box.due === undefined || box.due <= today);
|
||||
|
||||
if (this.boxesToReview.length === 0) {
|
||||
// No more boxes for this image, move to the next image
|
||||
this.nextImage();
|
||||
return;
|
||||
}
|
||||
|
||||
// Shuffle the boxes randomly
|
||||
this.boxesToReview = this.shuffleArray(this.boxesToReview);
|
||||
|
||||
// Initialize the array to track revealed boxes
|
||||
this.boxRevealed = new Array(this.boxesToReview.length).fill(false);
|
||||
|
||||
// Reset the current box index
|
||||
this.currentBoxIndex = 0;
|
||||
this.isShowingBox = false;
|
||||
|
||||
// Redraw the canvas
|
||||
this.drawCanvas();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns today's date in days since the UNIX epoch.
|
||||
*/
|
||||
getTodayInDays(): number {
|
||||
const epoch = new Date(1970, 0, 1); // Anki uses UNIX epoch
|
||||
const today = new Date();
|
||||
return Math.floor((today.getTime() - epoch.getTime()) / (1000 * 60 * 60 * 24));
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the current image and boxes on the canvas.
|
||||
* Boxes are displayed in red if hidden and green if revealed.
|
||||
*/
|
||||
drawCanvas(): void {
|
||||
const canvas = this.canvasRef.nativeElement;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx || !this.currentImageData) return;
|
||||
|
||||
const img = new Image();
|
||||
img.src = `/images/${this.currentImageData.bildid}/original.webp`;
|
||||
img.onload = () => {
|
||||
// Set the canvas size to the image size
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
|
||||
// Draw the image
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Draw the boxes
|
||||
this.boxesToReview.forEach((box, index) => {
|
||||
ctx.beginPath();
|
||||
ctx.rect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1);
|
||||
if ((this.currentBoxIndex === index && this.isShowingBox) || (box.due && box.due - this.getTodayInDays() > 0)) {
|
||||
// Box is currently revealed, no overlay
|
||||
return;
|
||||
} else if (this.currentBoxIndex === index && !this.isShowingBox) {
|
||||
// Box is revealed
|
||||
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Opaque green overlay
|
||||
} else {
|
||||
// Box is hidden
|
||||
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Opaque red overlay
|
||||
}
|
||||
ctx.fill();
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = 'black';
|
||||
ctx.stroke();
|
||||
});
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
console.error('Error loading image for canvas.');
|
||||
this.popoverService.show({
|
||||
title: 'Error',
|
||||
message: 'Error loading image for canvas.',
|
||||
});
|
||||
this.close.emit();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuffles an array randomly.
|
||||
* @param array The array to shuffle
|
||||
* @returns The shuffled array
|
||||
*/
|
||||
shuffleArray<T>(array: T[]): T[] {
|
||||
let currentIndex = array.length,
|
||||
randomIndex;
|
||||
|
||||
// While there are elements to shuffle
|
||||
while (currentIndex !== 0) {
|
||||
// Pick a remaining element
|
||||
randomIndex = Math.floor(Math.random() * currentIndex);
|
||||
currentIndex--;
|
||||
|
||||
// Swap it with the current element
|
||||
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current box being reviewed.
|
||||
*/
|
||||
get currentBox(): Box | null {
|
||||
if (this.currentBoxIndex < this.boxesToReview.length) {
|
||||
return this.boxesToReview[this.currentBoxIndex];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveals the content of the current box.
|
||||
*/
|
||||
showText(): void {
|
||||
if (this.currentBoxIndex >= this.boxesToReview.length) return;
|
||||
this.boxRevealed[this.currentBoxIndex] = true;
|
||||
this.isShowingBox = true;
|
||||
this.drawCanvas();
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the current box as "Again" and proceeds to the next box.
|
||||
*/
|
||||
async markAgain(): Promise<void> {
|
||||
await this.updateCard('again');
|
||||
this.coverCurrentBox();
|
||||
this.nextBox();
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the current box as "Good" and proceeds to the next box.
|
||||
*/
|
||||
async markGood(): Promise<void> {
|
||||
await this.updateCard('good');
|
||||
this.coverCurrentBox();
|
||||
this.nextBox();
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the current box as "Easy" and proceeds to the next box.
|
||||
*/
|
||||
async markEasy(): Promise<void> {
|
||||
await this.updateCard('easy');
|
||||
this.coverCurrentBox();
|
||||
this.nextBox();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the SRS data of the current box based on the given action.
|
||||
* @param action The action performed ('again', 'good', 'easy')
|
||||
*/
|
||||
async updateCard(action: 'again' | 'good' | 'easy'): Promise<void> {
|
||||
if (this.currentBoxIndex >= this.boxesToReview.length) return;
|
||||
|
||||
const box = this.boxesToReview[this.currentBoxIndex];
|
||||
const today = this.getTodayInDays();
|
||||
|
||||
// Calculate the new interval and possibly the new factor
|
||||
const { newIvl, newFactor, newReps, newLapses, newIsGraduated } = this.calculateNewInterval(box, action);
|
||||
|
||||
// Update the due date
|
||||
const nextDue = today + Math.floor(newIvl / 1440);
|
||||
|
||||
// Update the box object
|
||||
box.ivl = newIvl;
|
||||
box.factor = newFactor;
|
||||
box.reps = newReps;
|
||||
box.lapses = newLapses;
|
||||
box.due = nextDue;
|
||||
box.isGraduated = newIsGraduated;
|
||||
|
||||
// Send the update to the backend
|
||||
try {
|
||||
await lastValueFrom(this.deckService.updateBox(box));
|
||||
} catch (error) {
|
||||
console.error('Error updating box:', error);
|
||||
this.popoverService.show({
|
||||
title: 'Error',
|
||||
message: 'Error updating box.',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the new interval, factor, repetitions, and lapses based on the action.
|
||||
* @param box The current box
|
||||
* @param action The action ('again', 'good', 'easy')
|
||||
* @returns An object with the new values for ivl, factor, reps, and lapses
|
||||
*/
|
||||
calculateNewInterval(
|
||||
box: Box,
|
||||
action: 'again' | 'good' | 'easy',
|
||||
): {
|
||||
newIvl: number;
|
||||
newFactor: number;
|
||||
newReps: number;
|
||||
newLapses: number;
|
||||
newIsGraduated: boolean;
|
||||
} {
|
||||
const LEARNING_STEPS = {
|
||||
AGAIN: 1, // 1 minute
|
||||
GOOD: 10, // 10 minutes
|
||||
GRADUATION: 1440, // 1 day (1440 minutes)
|
||||
};
|
||||
|
||||
const EASY_BONUS = 1.3; // Zusätzlicher Easy-Multiplikator
|
||||
/* const FACTOR_CHANGES = {
|
||||
MIN: 1.3,
|
||||
MAX: 2.5,
|
||||
AGAIN: 0.85,
|
||||
EASY: 1.15
|
||||
}; */
|
||||
|
||||
let newIvl = box.ivl || 0;
|
||||
let newFactor = box.factor || 2.5;
|
||||
let newReps = box.reps || 0;
|
||||
let newLapses = box.lapses || 0;
|
||||
let newIsGraduated = box.isGraduated || false;
|
||||
|
||||
if (action === 'again') {
|
||||
newLapses++;
|
||||
newReps = 0;
|
||||
newIvl = LEARNING_STEPS.AGAIN;
|
||||
newIsGraduated = false;
|
||||
newFactor = Math.max(FACTOR_CHANGES.MIN, newFactor * FACTOR_CHANGES.AGAIN);
|
||||
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
|
||||
}
|
||||
|
||||
if (action === 'easy') {
|
||||
newReps++;
|
||||
|
||||
// Faktor zuerst aktualisieren
|
||||
const updatedFactor = Math.min(FACTOR_CHANGES.MAX, newFactor * FACTOR_CHANGES.EASY);
|
||||
|
||||
if (!newIsGraduated) {
|
||||
// Direkte Graduierung mit Easy
|
||||
newIsGraduated = true;
|
||||
newIvl = LEARNING_STEPS.GRADUATION; // 1 Tag (1440 Minuten)
|
||||
} else {
|
||||
// Anki-Formel für Easy in der Review-Phase
|
||||
newIvl = Math.round((newIvl + LEARNING_STEPS.GRADUATION / 2) * updatedFactor * EASY_BONUS);
|
||||
}
|
||||
|
||||
newFactor = updatedFactor;
|
||||
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
|
||||
}
|
||||
|
||||
// Handle 'good' action
|
||||
newReps++;
|
||||
|
||||
if (!newIsGraduated) {
|
||||
if (newReps === 1) {
|
||||
newIvl = LEARNING_STEPS.GOOD; // 10 Minuten
|
||||
} else {
|
||||
newIsGraduated = true;
|
||||
newIvl = LEARNING_STEPS.GRADUATION; // 1 Tag nach zweiter Good-Antwort
|
||||
}
|
||||
} else {
|
||||
// Standard-SR-Formel
|
||||
newIvl = Math.round(newIvl * newFactor);
|
||||
}
|
||||
|
||||
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the next interval based on the action and returns it as a string.
|
||||
* @param box The current box
|
||||
* @param action The action ('again', 'good', 'easy')
|
||||
* @returns The next interval as a string (e.g., "10 min", "2 d")
|
||||
*/
|
||||
getNextInterval(box: Box | null, action: 'again' | 'good' | 'easy'): string {
|
||||
if (!box) return '';
|
||||
|
||||
const { newIvl } = this.calculateNewInterval(box, action);
|
||||
|
||||
return this.formatInterval(newIvl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the interval as a string, either in minutes or days.
|
||||
* @param ivl The interval in days
|
||||
* @returns The formatted interval as a string
|
||||
*/
|
||||
formatInterval(minutes: number): string {
|
||||
if (minutes < 60) return `${minutes}min`;
|
||||
if (minutes < 1440) return `${Math.round(minutes / 60)}h`;
|
||||
return `${Math.round(minutes / 1440)}d`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Covers the current box again (hides it).
|
||||
*/
|
||||
coverCurrentBox(): void {
|
||||
this.boxRevealed[this.currentBoxIndex] = false;
|
||||
this.drawCanvas();
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves to the next box. If all boxes in the current round have been processed,
|
||||
* a new round is started.
|
||||
*/
|
||||
nextBox(): void {
|
||||
this.isShowingBox = false;
|
||||
|
||||
if (this.currentBoxIndex >= this.boxesToReview.length - 1) {
|
||||
// Round completed, start a new round
|
||||
this.initializeBoxesToReview();
|
||||
} else {
|
||||
// Move to the next box
|
||||
this.currentBoxIndex++;
|
||||
this.drawCanvas();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves to the next image in the deck.
|
||||
*/
|
||||
nextImage(): void {
|
||||
this.currentImageIndex++;
|
||||
this.loadImage(this.currentImageIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Skips to the next image in the deck.
|
||||
*/
|
||||
skipToNextImage(): void {
|
||||
if (this.currentImageIndex < this.deck.images.length - 1) {
|
||||
this.currentImageIndex++;
|
||||
this.loadImage(this.currentImageIndex);
|
||||
} else {
|
||||
this.popoverService.show({
|
||||
title: 'Information',
|
||||
message: 'This is the last image in the deck.',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the training and displays a completion message.
|
||||
*/
|
||||
endTraining(): void {
|
||||
this.isTrainingFinished = true;
|
||||
this.popoverService.show({
|
||||
title: 'Information',
|
||||
message: 'Training completed!',
|
||||
});
|
||||
this.close.emit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the user if they want to end the training and closes it if confirmed.
|
||||
*/
|
||||
closeTraining(): void {
|
||||
this.popoverService.show({
|
||||
title: 'End Training',
|
||||
message: 'Do you really want to end the training?',
|
||||
confirmText: 'End Training',
|
||||
onConfirm: (inputValue?: string) => this.close.emit(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the progress of the training, e.g., "Image 2 of 5".
|
||||
*/
|
||||
get progress(): string {
|
||||
return `Image ${this.currentImageIndex + 1} of ${this.deck.images.length}`;
|
||||
}
|
||||
}
|
||||
19
src/assets/logo.svg
Normal file
19
src/assets/logo.svg
Normal file
@@ -0,0 +1,19 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
|
||||
<!-- Hintergrund -->
|
||||
<rect width="40" height="40" fill="#ffffff"/>
|
||||
|
||||
<!-- Basis H - Rot -->
|
||||
<path d="M6 4 H14 V16 H26 V4 H34 V36 H26 V24 H14 V36 H6 Z" fill="#FF4F4F"/>
|
||||
|
||||
<!-- Grünes Element -->
|
||||
<path d="M6 4 H14 V16 H26 V4 H34 V20 H6 Z" fill="#2ECC40"/>
|
||||
|
||||
<!-- Gelber Bereich -->
|
||||
<path d="M10 8 H16 V16 H24 V8 H30 V32 H24 V24 H16 V32 H10 Z" fill="#FFBE00"/>
|
||||
|
||||
<!-- Jadegrüner Bereich -->
|
||||
<path d="M12 12 H18 V16 H22 V12 H28 V28 H22 V24 H18 V28 H12 Z" fill="#00C4A7"/>
|
||||
|
||||
<!-- Innerstes blaues Element -->
|
||||
<path d="M14 14 H19 V16 H21 V14 H26 V26 H21 V24 H19 V26 H14 Z" fill="#0077B3"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 682 B |
@@ -1,13 +1,22 @@
|
||||
<!doctype html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Haiky</title>
|
||||
<base href="/">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="icon" type="image/x-icon" href="favicon.ico">
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Vokabeltraining</title>
|
||||
<base href="/" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png" />
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png" />
|
||||
<link rel="icon" type="image/png" sizes="48x48" href="favicon-48x48.png" />
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
height: 100vh;
|
||||
background: rgba(0, 119, 179, 0.1);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<app-root></app-root>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
6
src/proxy.conf.json
Normal file
6
src/proxy.conf.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"/api": {
|
||||
"target": "http://localhost:5000",
|
||||
"secure": false
|
||||
}
|
||||
}
|
||||
@@ -1 +1,4 @@
|
||||
/* You can add global styles to this file, and also import other style files */
|
||||
@use 'tailwindcss' as *;
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user