Compare commits

...

6 Commits

Author SHA1 Message Date
Andreas Knuth f968f2ab38 translate to english 2025-01-15 00:05:57 +00:00
Andreas Knuth 156d017730 3column design, borders 2025-01-12 16:34:48 +00:00
aknuth 26088f58c9 isGraduated eingebaut SRS Berechnung umgebaut 2024-12-13 11:59:33 +01:00
aknuth 05bfd4f3eb Anzeige des nächsten Intervals 2024-12-12 18:26:01 +01:00
aknuth d5ac4d6f26 SRS 2. Teil 2024-12-12 17:20:43 +01:00
aknuth ac69a11db5 move to SRS Algo 2024-12-11 21:33:52 +01:00
14 changed files with 528 additions and 270 deletions

View File

@ -8,16 +8,16 @@ import { DeckListComponent } from './deck-list.component';
selector: 'app-root', selector: 'app-root',
template: ` template: `
<div class="container mx-auto p-4"> <div class="container mx-auto p-4">
<h1 class="text-3xl font-bold text-center mb-8">Vokabeltraining</h1> <h1 class="text-3xl font-bold text-center mb-8">Vocabulary Training</h1>
<app-deck-list></app-deck-list> <app-deck-list></app-deck-list>
</div> </div>
`, `,
standalone: true, standalone: true,
imports: [ CommonModule, DeckListComponent] imports: [CommonModule, DeckListComponent]
}) })
export class AppComponent { export class AppComponent {
title = 'vokabeltraining'; title = 'vocabulary-training';
ngOnInit(): void { ngOnInit(): void {
initFlowbite(); initFlowbite();
} }
} }

View File

@ -1,4 +1,3 @@
<!-- src/app/create-deck-modal.component.html -->
<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 #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 w-full h-full max-w-md md:h-auto">
<div class="relative bg-white rounded-lg shadow"> <div class="relative bg-white rounded-lg shadow">
@ -6,17 +5,17 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <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> <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> </svg>
<span class="sr-only">Schließen</span> <span class="sr-only">Close</span>
</button> </button>
<div class="p-6"> <div class="p-6">
<h3 class="mb-4 text-xl font-medium text-gray-900">Neues Deck erstellen</h3> <h3 class="mb-4 text-xl font-medium text-gray-900">Create New Deck</h3>
<form (submit)="createDeck($event)"> <form (submit)="createDeck($event)">
<div class="mb-4"> <div class="mb-4">
<label for="deckName" class="block text-sm font-medium text-gray-700">Deck-Name</label> <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" /> <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> </div>
<button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"> <button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Erstellen Create
</button> </button>
</form> </form>
</div> </div>

View File

@ -1,4 +1,3 @@
// src/app/create-deck-modal.component.ts
import { Component, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; import { Component, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { DeckService } from '../deck.service'; import { DeckService } from '../deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@ -30,7 +29,7 @@ export class CreateDeckModalComponent implements AfterViewInit {
createDeck(event: Event): void { createDeck(event: Event): void {
event.preventDefault(); event.preventDefault();
if (this.deckName.trim() === '') { if (this.deckName.trim() === '') {
alert('Bitte einen Deck-Namen eingeben.'); alert('Please enter a deck name.');
return; return;
} }
@ -41,8 +40,8 @@ export class CreateDeckModalComponent implements AfterViewInit {
this.modal.hide(); this.modal.hide();
}, },
error: (err) => { error: (err) => {
console.error('Fehler beim Erstellen des Decks', err); console.error('Error creating deck', err);
alert('Fehler beim Erstellen des Decks.'); alert('Error creating deck.');
} }
}); });
} }
@ -50,5 +49,4 @@ export class CreateDeckModalComponent implements AfterViewInit {
closeModal(): void { closeModal(): void {
this.modal.hide(); this.modal.hide();
} }
} }

View File

@ -1,79 +1,78 @@
<!-- src/app/deck-list.component.html -->
<div> <div>
<!-- Button zum Erstellen eines neuen Decks --> <!-- Button to create a new deck -->
<div class="flex justify-end mb-4"> <div class="flex justify-end mb-4">
<button (click)="openCreateDeckModal()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600"> <button (click)="openCreateDeckModal()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Neues Deck erstellen Create New Deck
</button> </button>
</div> </div>
<!-- Decks anzeigen --> <!-- Display decks -->
<div class="flex flex-wrap gap-6"> <div class="flex flex-wrap">
<div *ngFor="let deck of decks" class="bg-white shadow rounded-lg p-6 w-full md:w-1/2 lg:w-1/3 flex flex-col"> <div *ngFor="let deck of decks" class="bg-white shadow rounded-lg p-6 w-full md:w-1/2 lg:w-1/3 flex flex-col border-dashed border-2 border-indigo-600">
<!-- Deck-Header mit Toggle-Button --> <!-- Deck header with toggle button -->
<div class="flex justify-between items-center mb-4"> <div class="flex justify-between items-center mb-4">
<div class="flex items-center space-x-2"> <div class="flex items-center space-x-2">
<h2 class="text-xl font-semibold">{{ deck.name }}</h2> <h2 class="text-xl font-semibold">{{ deck.name }}</h2>
<span class="text-gray-600">({{ deck.images.length }} Bilder)</span> <span class="text-gray-600">({{ deck.images.length }} images)</span>
</div> </div>
<button (click)="toggleDeckExpansion(deck.id)" class="text-gray-500 hover:text-gray-700 focus:outline-none" title="Deck ein-/ausklappen"> <button (click)="toggleDeckExpansion(deck.name)" class="text-gray-500 hover:text-gray-700 focus:outline-none" title="Expand/Collapse Deck">
<svg *ngIf="!isDeckExpanded(deck.id)" 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"> <svg *ngIf="!isDeckExpanded(deck.name)" 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="M19 9l-7 7-7-7" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg> </svg>
<svg *ngIf="isDeckExpanded(deck.id)" 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"> <svg *ngIf="isDeckExpanded(deck.name)" 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="M19 9l-7 7-7-7" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg> </svg>
</button> </button>
</div> </div>
<!-- Bildliste und Action-Buttons nur anzeigen, wenn das Deck erweitert ist und kein Training aktiv ist --> <!-- Image list and action buttons only shown if the deck is expanded and no training is active -->
<ng-container *ngIf="isDeckExpanded(deck.id) && !selectedDeck"> <ng-container *ngIf="isDeckExpanded(deck.name) && !selectedDeck">
<!-- Liste der Bilder mit Anzahl der Boxen und Icons --> <!-- List of images with number of boxes and icons -->
<ul class="mb-4"> <ul class="mb-4">
<li *ngFor="let image of deck.images" class="flex justify-between items-center py-2 border-b last:border-b-0"> <li *ngFor="let image of deck.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="flex items-center space-x-2">
<div class="relative group"> <div class="relative group">
<!-- Tooltip Inhalt (Bild) --> <!-- Tooltip content (image) -->
<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"> <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="/api/debug_image/{{image.id}}/thumbnail.jpg" alt="{{ image.name }}" class="w-full h-auto object-cover"> <img src="/api/debug_image/{{image.id}}/thumbnail.jpg" alt="{{ image.name }}" class="w-full h-auto object-cover">
</div> </div>
<!-- Bildname mit Tooltip --> <!-- Image name with tooltip -->
<span class="font-medium cursor-pointer"> <span class="font-medium cursor-pointer">
{{ image.name }} {{ image.name }}
</span> </span>
</div> </div>
<span class="text-gray-600">({{ image.boxes.length }} Boxen)</span> <span class="text-gray-600">({{ image.boxes.length }} boxes)</span>
</div> </div>
<div class="flex space-x-2"> <div class="flex space-x-2">
<!-- Edit Icon --> <!-- Edit Icon -->
<button (click)="editImage(deck, image)" class="text-blue-500 hover:text-blue-700" title="Bild bearbeiten"> <button (click)="editImage(deck, 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"> <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" /> <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> </svg>
</button> </button>
<!-- Delete Icon --> <!-- Delete Icon -->
<button (click)="deleteImage(deck, image)" class="text-red-500 hover:text-red-700" title="Bild löschen"> <button (click)="deleteImage(deck, 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"> <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" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg> </svg>
</button> </button>
<!-- Move Icon --> <!-- Move Icon -->
<button (click)="openMoveImageModal(deck, image)" class="text-yellow-500 hover:text-yellow-700" title="Bild verschieben"> <button (click)="openMoveImageModal(deck, 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"> <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" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg> </svg>
</button> </button>
</div> </div>
</li> </li>
</ul> </ul>
<!-- Action-Buttons --> <!-- Action buttons -->
<div class="flex space-x-2"> <div class="flex space-x-2">
<button (click)="openTraining(deck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"> <button (click)="openTraining(deck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Training starten Start Training
</button> </button>
<button (click)="openUploadImageModal(deck.name)" class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600"> <button (click)="openUploadImageModal(deck.name)" class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Bild hinzufügen Add Image
</button> </button>
</div> </div>
</ng-container> </ng-container>
@ -84,18 +83,17 @@
<app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal> <app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal>
<!-- UploadImageModalComponent --> <!-- UploadImageModalComponent -->
<!-- <app-upload-image-modal [deckName]="currentUploadDeckName" (imageUploaded)="loadDecks()"></app-upload-image-modal> --> <app-upload-image-modal (imageUploaded)="onImageUploaded($event)"></app-upload-image-modal>
<app-upload-image-modal (imageUploaded)="onImageUploaded($event)"> </app-upload-image-modal>
<app-edit-image-modal *ngIf="imageData" [deckName]="currentUploadDeckName" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal> <app-edit-image-modal *ngIf="imageData" [deckName]="currentUploadDeckName" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal>
<!-- TrainingComponent --> <!-- TrainingComponent -->
<app-training *ngIf="selectedDeck" [deck]="selectedDeck" (close)="closeTraining()"></app-training> <app-training *ngIf="selectedDeck" [deck]="selectedDeck" (close)="closeTraining()"></app-training>
<!-- MoveImageModalComponent --> <!-- MoveImageModalComponent -->
<app-move-image-modal <app-move-image-modal
*ngIf="imageToMove" *ngIf="imageToMove"
[image]="imageToMove.image" [image]="imageToMove.image"
[sourceDeck]="imageToMove.sourceDeck" [sourceDeck]="imageToMove.sourceDeck"
[decks]="decks" [decks]="decks"
(moveCompleted)="onImageMoved()" (moveCompleted)="onImageMoved()"
(closed)="imageToMove = null"> (closed)="imageToMove = null">
</app-move-image-modal> </app-move-image-modal>
</div> </div>

View File

@ -1,4 +1,3 @@
// src/app/deck-list.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { Component, OnInit, ViewChild } from '@angular/core';
import { DeckService, Deck, DeckImage } from './deck.service'; import { DeckService, Deck, DeckImage } from './deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@ -19,7 +18,7 @@ import { MoveImageModalComponent } from './move-image-modal/move-image-modal.com
UploadImageModalComponent, UploadImageModalComponent,
TrainingComponent, TrainingComponent,
EditImageModalComponent, EditImageModalComponent,
MoveImageModalComponent, // Hinzufügen der neuen Komponente MoveImageModalComponent, // Adding the new component
UploadImageModalComponent UploadImageModalComponent
] ]
}) })
@ -36,10 +35,10 @@ export class DeckListComponent implements OnInit {
currentUploadDeckName: string = ''; currentUploadDeckName: string = '';
// Set zur Verfolgung erweiterter Decks // Set to track expanded decks
expandedDecks: Set<number> = new Set<number>(); expandedDecks: Set<string> = new Set<string>();
// State für das Verschieben von Bildern // State for moving images
imageToMove: { image: DeckImage, sourceDeck: Deck } | null = null; imageToMove: { image: DeckImage, sourceDeck: Deck } | null = null;
constructor(private deckService: DeckService) { } constructor(private deckService: DeckService) { }
@ -52,56 +51,56 @@ export class DeckListComponent implements OnInit {
loadDecks(): void { loadDecks(): void {
this.deckService.getDecks().subscribe({ this.deckService.getDecks().subscribe({
next: (data) => this.decks = data, next: (data) => this.decks = data,
error: (err) => console.error('Fehler beim Laden der Decks', err) error: (err) => console.error('Error loading decks', err)
}); });
} }
deleteDeck(deckName: string): void { deleteDeck(deckName: string): void {
if (!confirm(`Bist du sicher, dass du das Deck "${deckName}" löschen möchtest?`)) { if (!confirm(`Are you sure you want to delete the deck "${deckName}"?`)) {
return; return;
} }
this.deckService.deleteDeck(deckName).subscribe({ this.deckService.deleteDeck(deckName).subscribe({
next: () => this.loadDecks(), next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Decks', err) error: (err) => console.error('Error deleting deck', err)
}); });
} }
deleteImage(deck: Deck, image: DeckImage): void { deleteImage(deck: Deck, image: DeckImage): void {
if (!confirm(`Bist du sicher, dass du das Bild "${image.name}" löschen möchtest?`)) { if (!confirm(`Are you sure you want to delete the image "${image.name}"?`)) {
return; return;
} }
const imageId = image.id; const imageId = image.id;
this.deckService.deleteImage(imageId).subscribe({ this.deckService.deleteImage(imageId).subscribe({
next: () => this.loadDecks(), next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Bildes', err) error: (err) => console.error('Error deleting image', err)
}); });
} }
editImage(deck: Deck, image: DeckImage): void { editImage(deck: Deck, image: DeckImage): void {
let imageSrc = null let imageSrc = null;
this.currentUploadDeckName = deck.name; this.currentUploadDeckName = deck.name;
fetch(`/api/debug_image/${image.id}/original_compressed.jpg`) fetch(`/api/debug_image/${image.id}/original_compressed.jpg`)
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
throw new Error('Netzwerkantwort war nicht ok'); throw new Error('Network response was not ok');
} }
return response.blob(); return response.blob();
}) })
.then(blob => { .then(blob => {
const reader = new FileReader(); const reader = new FileReader();
reader.onloadend = () => { reader.onloadend = () => {
imageSrc = reader.result; // Base64-String imageSrc = reader.result; // Base64 string
this.imageData = { imageSrc, deckImage: image } this.imageData = { imageSrc, deckImage: image };
}; };
reader.readAsDataURL(blob); reader.readAsDataURL(blob);
}) })
.catch(error => { .catch(error => {
console.error('Fehler beim Laden des Bildes:', error); console.error('Error loading image:', error);
}); });
} }
openTraining(deck: Deck): void { openTraining(deck: Deck): void {
this.selectedDeck = deck; this.selectedDeck = deck;
} }
@ -121,71 +120,71 @@ export class DeckListComponent implements OnInit {
this.uploadImageModal.open(); this.uploadImageModal.open();
} }
// Methode zum Umschalten der Deck-Erweiterung // Method to toggle deck expansion
toggleDeckExpansion(deckId: number): void { toggleDeckExpansion(deckName: string): void {
if (this.expandedDecks.has(deckId)) { if (this.expandedDecks.has(deckName)) {
this.expandedDecks.delete(deckId); this.expandedDecks.delete(deckName);
} else { } else {
this.expandedDecks.add(deckId); this.expandedDecks.add(deckName);
} }
this.saveExpandedDecks(); this.saveExpandedDecks();
} }
// Methode zur Überprüfung, ob ein Deck erweitert ist // Method to check if a deck is expanded
isDeckExpanded(deckId: number): boolean { isDeckExpanded(deckName: string): boolean {
return this.expandedDecks.has(deckId); return this.expandedDecks.has(deckName);
} }
// Laden der erweiterten Decks aus dem sessionStorage // Load expanded decks from sessionStorage
loadExpandedDecks(): void { loadExpandedDecks(): void {
const stored = sessionStorage.getItem('expandedDecks'); const stored = sessionStorage.getItem('expandedDecks');
if (stored) { if (stored) {
try { try {
const parsed: number[] = JSON.parse(stored); const parsed: string[] = JSON.parse(stored);
this.expandedDecks = new Set<number>(parsed); this.expandedDecks = new Set<string>(parsed);
} catch (e) { } catch (e) {
console.error('Fehler beim Parsen der erweiterten Decks aus sessionStorage', e); console.error('Error parsing expanded decks from sessionStorage', e);
} }
} else { } else {
// Wenn keine Daten gespeichert sind, alle Decks standardmäßig nicht erweitern // If no data is stored, do not expand any decks by default
this.expandedDecks = new Set<number>(); this.expandedDecks = new Set<string>();
} }
} }
// Speichern der erweiterten Decks in das sessionStorage // Save expanded decks to sessionStorage
saveExpandedDecks(): void { saveExpandedDecks(): void {
const expandedArray = Array.from(this.expandedDecks); const expandedArray = Array.from(this.expandedDecks);
sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray)); sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray));
} }
// Funktion zum Öffnen des Upload Modals (kann durch einen Button ausgelöst werden) // Function to open the upload modal (can be triggered by a button)
openUploadModal(): void { openUploadModal(): void {
this.uploadImageModal.open(); this.uploadImageModal.open();
} }
// Handler für das imageUploaded Event // Handler for the imageUploaded event
onImageUploaded(imageData: any): void { onImageUploaded(imageData: any): void {
this.imageData = imageData; this.imageData = imageData;
} }
onClosed(){ onClosed() {
this.imageData = null; this.imageData = null;
} }
async onImageSaved() { async onImageSaved() {
// Handle das Speichern der Bilddaten, z.B. aktualisiere die Liste der Bilder // Handle saving the image data, e.g., update the list of images
this.imageData = null; this.imageData = null;
this.decks = await firstValueFrom(this.deckService.getDecks()) this.decks = await firstValueFrom(this.deckService.getDecks());
} }
// Methode zum Öffnen des MoveImageModal // Method to open the MoveImageModal
openMoveImageModal(deck: Deck, image: DeckImage): void { openMoveImageModal(deck: Deck, image: DeckImage): void {
this.imageToMove = { image, sourceDeck: deck }; this.imageToMove = { image, sourceDeck: deck };
} }
// Handler für das moveCompleted Event // Handler for the moveCompleted event
onImageMoved(): void { onImageMoved(): void {
this.imageToMove = null; this.imageToMove = null;
this.loadDecks(); this.loadDecks();
} }
} }

View File

@ -1,10 +1,8 @@
// src/app/deck.service.ts
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { map, Observable, switchMap } from 'rxjs'; import { map, Observable, switchMap } from 'rxjs';
export interface Deck { export interface Deck {
id: number; // Hinzugefügt
name: string; name: string;
images: DeckImage[]; images: DeckImage[];
} }
@ -12,14 +10,21 @@ export interface Deck {
export interface DeckImage { export interface DeckImage {
boxes: Box[]; boxes: Box[];
name: string; name: string;
id:string; id: string;
} }
export interface Box { export interface Box {
x1:number; id?: number;
x2:number; x1: number;
y1:number; x2: number;
y2:number; y1: number;
y2: number;
due?: number;
ivl?: number;
factor?: number;
reps?: number;
lapses?: number;
isGraduated?: boolean;
} }
export interface BackendBox { export interface BackendBox {
@ -33,13 +38,13 @@ export interface BackendBox {
y2: number; y2: number;
} }
// Definiert ein einzelnes Punktpaar [x, y] // Defines a single point pair [x, y]
type OcrPoint = [number, number]; type OcrPoint = [number, number];
// Definiert die Box als Array von vier Punkten // Defines the box as an array of four points
type OcrBox = [OcrPoint, OcrPoint, OcrPoint, OcrPoint]; type OcrBox = [OcrPoint, OcrPoint, OcrPoint, OcrPoint];
// Interface für jedes JSON-Objekt // Interface for each JSON object
export interface OcrResult { export interface OcrResult {
box: OcrBox; box: OcrBox;
confidence: number; confidence: number;
@ -58,12 +63,12 @@ export class DeckService {
getDecks(): Observable<Deck[]> { getDecks(): Observable<Deck[]> {
return this.http.get<any[]>(this.apiUrl).pipe( return this.http.get<any[]>(this.apiUrl).pipe(
map(decks => decks.map(deck => ({ map(decks => decks.map(deck => ({
id: deck.id, // Annahme: Jeder Deck hat eine eindeutige ID
name: deck.name, name: deck.name,
images: this.groupImagesByName(deck.images) images: this.groupImagesByName(deck.images)
}))) })))
); );
} }
private groupImagesByName(images: any[]): DeckImage[] { private groupImagesByName(images: any[]): DeckImage[] {
const imageMap: { [key: string]: DeckImage } = {}; const imageMap: { [key: string]: DeckImage } = {};
@ -71,21 +76,29 @@ export class DeckService {
if (!imageMap[image.id]) { if (!imageMap[image.id]) {
imageMap[image.id] = { imageMap[image.id] = {
name: image.name, name: image.name,
id:image.id, id: image.id,
boxes: [] boxes: []
}; };
} }
imageMap[image.id].boxes.push({ imageMap[image.id].boxes.push({
id: image.boxid,
x1: image.x1, x1: image.x1,
x2: image.x2, x2: image.x2,
y1: image.y1, y1: image.y1,
y2: image.y2 y2: image.y2,
due: image.due,
ivl: image.ivl,
factor: image.factor,
reps: image.reps,
lapses: image.lapses,
isGraduated: image.isGraduated ? true : false
}); });
}); });
return Object.values(imageMap); return Object.values(imageMap);
} }
getDeck(deckname:string): Observable<Deck> {
getDeck(deckname: string): Observable<Deck> {
return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`); return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`);
} }
@ -97,17 +110,21 @@ export class DeckService {
return this.http.delete(`${this.apiUrl}/${encodeURIComponent(deckName)}`); return this.http.delete(`${this.apiUrl}/${encodeURIComponent(deckName)}`);
} }
saveImageData(data:any): Observable<any> { saveImageData(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/image`, data); return this.http.post(`${this.apiUrl}/image`, data);
} }
// Neue Methode zum Löschen eines Bildes // New method to delete an image
deleteImage(imageName: string): Observable<any> { deleteImage(imageName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/image/${imageName}`); return this.http.delete(`${this.apiUrl}/image/${imageName}`);
} }
// Neue Methode zum Verschieben eines Bildes // New method to move an image
moveImage(imageId: string, targetDeckId: number): Observable<any> { moveImage(imageId: string, targetDeckId: number): Observable<any> {
return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId }); 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);
}
}

View File

@ -1,4 +1,3 @@
<!-- src/app/edit-image-modal.component.html -->
<div #editImageModal id="editImageModal" 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 #editImageModal id="editImageModal" 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 h-full contents">
<div class="relative bg-white rounded-lg shadow"> <div class="relative bg-white rounded-lg shadow">
@ -6,12 +5,12 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <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> <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> </svg>
<span class="sr-only">Schließen</span> <span class="sr-only">Close</span>
</button> </button>
<div class="p-6 relative"> <div class="p-6 relative">
<!-- Überschrift mit Boxanzahl --> <!-- Header with box count -->
<h3 class="mb-4 text-xl font-medium text-gray-900"> <h3 class="mb-4 text-xl font-medium text-gray-900">
Bild bearbeiten <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'en' : '' }})</span> Edit Image <span *ngIf="boxes.length > 0">({{ boxes.length }} Box{{ boxes.length > 1 ? 'es' : '' }})</span>
</h3> </h3>
<!-- Canvas --> <!-- Canvas -->
@ -19,16 +18,16 @@
<canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas> <canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas>
</div> </div>
<!-- Buttons unter dem Canvas --> <!-- Buttons below the canvas -->
<div class="mt-4 flex justify-between"> <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"> <button (click)="save()" class="bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Save Save
</button> </button>
<button (click)="addNewBox()" class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"> <button (click)="addNewBox()" class="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Neue Box New Box
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -12,11 +12,11 @@ import { DeckImage, DeckService, OcrResult } from '../deck.service';
imports: [CommonModule] imports: [CommonModule]
}) })
export class EditImageModalComponent implements AfterViewInit, OnDestroy { export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// Konstante für die Boxfarbe // Constant for box color
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Rot mit Transparenz private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Red with transparency
@Input() deckName: string = ''; @Input() deckName: string = '';
@Input() imageData : {imageSrc:string|ArrayBuffer|null, deckImage:DeckImage|null} = {imageSrc:null,deckImage:null}; @Input() imageData: { imageSrc: string | ArrayBuffer | null, deckImage: DeckImage | null } = { imageSrc: null, deckImage: null };
@Output() imageSaved = new EventEmitter<void>(); @Output() imageSaved = new EventEmitter<void>();
@Output() closed = new EventEmitter<void>(); @Output() closed = new EventEmitter<void>();
@ViewChild('editImageModal') modalElement!: ElementRef; @ViewChild('editImageModal') modalElement!: ElementRef;
@ -35,11 +35,11 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
constructor(private deckService: DeckService) { } constructor(private deckService: DeckService) { }
async ngAfterViewInit() { async ngAfterViewInit() {
this.modal = new Modal(this.modalElement.nativeElement,{ this.modal = new Modal(this.modalElement.nativeElement, {
onHide: () => { onHide: () => {
this.closed.emit(); this.closed.emit();
}}, }
); });
this.maxCanvasWidth = window.innerWidth * 0.6; this.maxCanvasWidth = window.innerWidth * 0.6;
this.maxCanvasHeight = window.innerHeight * 0.6; this.maxCanvasHeight = window.innerHeight * 0.6;
@ -89,13 +89,13 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
async processImage(): Promise<void> { async processImage(): Promise<void> {
try { try {
if (!this.imageData){ if (!this.imageData) {
return; return;
} }
this.canvas = new fabric.Canvas(this.canvasElement.nativeElement); this.canvas = new fabric.Canvas(this.canvasElement.nativeElement);
// Hintergrundbild setzen // Set background image
const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string); const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string);
const originalWidth = backgroundImage.width!; const originalWidth = backgroundImage.width!;
@ -120,7 +120,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.boxes = []; this.boxes = [];
// Boxen hinzufügen // Add boxes
this.imageData.deckImage?.boxes.forEach(box => { this.imageData.deckImage?.boxes.forEach(box => {
const rect = new fabric.Rect({ const rect = new fabric.Rect({
@ -128,7 +128,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
top: box.y1 * scaleFactor, top: box.y1 * scaleFactor,
width: (box.x2 - box.x1) * scaleFactor, width: (box.x2 - box.x1) * scaleFactor,
height: (box.y2 - box.y1) * scaleFactor, height: (box.y2 - box.y1) * scaleFactor,
fill: this.BOX_COLOR, // Verwendung der Konstante fill: this.BOX_COLOR, // Use the constant
selectable: true, selectable: true,
hasControls: true, hasControls: true,
hasBorders: true, hasBorders: true,
@ -159,7 +159,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// this.detectedText = ocrResults.map(result => result.text).join('\n'); // this.detectedText = ocrResults.map(result => result.text).join('\n');
} catch (error) { } catch (error) {
console.error('Fehler bei der Bildverarbeitung:', error); console.error('Error processing image:', error);
} }
} }
@ -221,7 +221,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
top: (canvasHeight - boxHeight) / 2, top: (canvasHeight - boxHeight) / 2,
width: boxWidth, width: boxWidth,
height: boxHeight, height: boxHeight,
fill: this.BOX_COLOR, // Verwendung der Konstante fill: this.BOX_COLOR, // Use the constant
selectable: true, selectable: true,
hasControls: true, hasControls: true,
hasBorders: true, hasBorders: true,
@ -252,8 +252,8 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
} }
save(): void { save(): void {
// Hier implementierst du die Logik zum Speichern der Bilddaten // Implement the logic to save the image data here
// Zum Beispiel über einen Service oder direkt hier // For example, via a service or directly here
const data = { const data = {
deckname: this.deckName, deckname: this.deckName,
bildname: this.imageData.deckImage?.name, // this.imageFile?.name, bildname: this.imageData.deckImage?.name, // this.imageFile?.name,
@ -266,10 +266,10 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.closeModal(); this.closeModal();
}, },
error: (err) => { error: (err) => {
console.error('Fehler beim Speichern des Bildes:', err); console.error('Error saving image:', err);
alert('Fehler beim Speichern des Bildes.'); alert('Error saving image.');
this.closeModal(); this.closeModal();
} }
}); });
} }
} }

View File

@ -1,24 +1,22 @@
<!-- src/app/move-image-modal.component.html -->
<div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50"> <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"> <div class="bg-white rounded-lg shadow-lg w-96 p-6">
<h2 class="text-xl font-semibold mb-4">Bild verschieben</h2> <h2 class="text-xl font-semibold mb-4">Move Image</h2>
<p class="mb-4">Wähle das Zieldeck für das Bild <strong>{{ image.name }}</strong> aus.</p> <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"> <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"> <option *ngFor="let deck of decks" [value]="deck.name" [disabled]="deck.name === sourceDeck.name">
{{ deck.name }} {{ deck.name }}
</option> </option>
</select> </select>
<div class="flex justify-end space-x-2"> <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"> <button (click)="close()" class="bg-gray-500 text-white py-2 px-4 rounded hover:bg-gray-600">
Abbrechen Cancel
</button> </button>
<button <button
(click)="moveImage()" (click)="moveImage()"
[disabled]="!selectedDeckId" [disabled]="!selectedDeckId"
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600"> class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
Verschieben Move
</button> </button>
</div>
</div> </div>
</div> </div>
</div>

View File

@ -1,7 +1,5 @@
// src/app/move-image-modal.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core'; import { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { DeckImage, Deck, DeckService } from '../deck.service'; import { DeckImage, Deck, DeckService } from '../deck.service';
@ -33,8 +31,8 @@ export class MoveImageModalComponent {
this.close(); this.close();
}, },
error: (err) => { error: (err) => {
console.error('Fehler beim Verschieben des Bildes:', err); console.error('Error moving image:', err);
alert('Fehler beim Verschieben des Bildes.'); alert('Error moving image.');
} }
}); });
} }
@ -42,4 +40,4 @@ export class MoveImageModalComponent {
close(): void { close(): void {
this.closed.emit(); this.closed.emit();
} }
} }

View File

@ -1,55 +1,62 @@
<!-- src/app/training.component.html -->
<div class="mt-10"> <div class="mt-10">
<h2 class="text-2xl font-bold mb-4">Training: {{ deck.name }}</h2> <h2 class="text-2xl font-bold mb-4">Training: {{ deck.name }}</h2>
<div class="bg-white shadow rounded-lg p-6 flex flex-col items-center"> <div class="bg-white shadow rounded-lg p-6 flex flex-col items-center">
<canvas #canvas class="mb-4 border max-h-[50vh]"></canvas> <canvas #canvas class="mb-4 border max-h-[50vh]"></canvas>
<div class="flex space-x-4 mb-4"> <div class="flex space-x-4 mb-4">
<!-- Anzeigen Button --> <!-- Show Button -->
<button <button
(click)="showText()" (click)="showText()"
class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600" class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600"
[disabled]="isShowingBox || currentBoxIndex >= boxesToReview.length" [disabled]="isShowingBox || currentBoxIndex >= boxesToReview.length"
> >
Anzeigen Show
</button> </button>
<!-- Gewusst Button --> <!-- Again Button -->
<button <button
(click)="markKnown()" (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" class="bg-blue-500 disabled:bg-blue-200 text-white py-2 px-4 rounded hover:bg-blue-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length" [disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
> >
Gewusst Good ({{ getNextInterval(currentBox, 'good') }})
</button> </button>
<!-- Nicht gewusst Button --> <!-- Easy Button -->
<button <button
(click)="markUnknown()" (click)="markEasy()"
class="bg-red-500 disabled:bg-red-200 text-white py-2 px-4 rounded hover:bg-red-600" class="bg-green-500 disabled:bg-green-200 text-white py-2 px-4 rounded hover:bg-green-600"
[disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length" [disabled]="!isShowingBox || currentBoxIndex >= boxesToReview.length"
> >
Nicht gewusst Easy ({{ getNextInterval(currentBox, 'easy') }})
</button> </button>
<!-- Nächstes Bild Button --> <!-- Next Image Button -->
<button <button
(click)="skipToNextImage()" (click)="skipToNextImage()"
class="bg-yellow-500 disabled:bg-yellow-200 text-white py-2 px-4 rounded hover:bg-yellow-600" class="bg-yellow-500 disabled:bg-yellow-200 text-white py-2 px-4 rounded hover:bg-yellow-600"
[disabled]="currentImageIndex >= deck.images.length" [disabled]="currentImageIndex >= deck.images.length"
> >
Nächstes Bild Next Image
</button> </button>
</div> </div>
<p class="mt-2">{{ progress }}</p> <p class="mt-2">{{ progress }}</p>
<p class="mt-2">Gewusst: {{ knownCount }} | Nicht gewusst: {{ unknownCount }}</p>
<button <button
(click)="closeTraining()" (click)="closeTraining()"
class="mt-4 text-gray-500 hover:text-gray-700 underline" class="mt-4 text-gray-500 hover:text-gray-700 underline"
> >
Training beenden End Training
</button> </button>
</div> </div>
</div> </div>

View File

@ -1,10 +1,21 @@
// src/app/training.component.ts
import { Component, Input, Output, EventEmitter, OnInit, ViewChild, ElementRef } from '@angular/core'; import { Component, Input, Output, EventEmitter, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Deck, DeckImage, DeckService, Box } from '../deck.service'; import { Deck, DeckImage, DeckService, Box } from '../deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { switchMap } from 'rxjs/operators'; import { lastValueFrom } from 'rxjs';
import { forkJoin } from 'rxjs';
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({ @Component({
selector: 'app-training', selector: 'app-training',
templateUrl: './training.component.html', templateUrl: './training.component.html',
@ -15,35 +26,37 @@ export class TrainingComponent implements OnInit {
@Input() deck!: Deck; @Input() deck!: Deck;
@Output() close = new EventEmitter<void>(); @Output() close = new EventEmitter<void>();
@ViewChild('canvas',{static : false}) canvasRef!: ElementRef<HTMLCanvasElement>; @ViewChild('canvas', { static: false }) canvasRef!: ElementRef<HTMLCanvasElement>;
currentImageIndex: number = 0; currentImageIndex: number = 0;
currentImageData: DeckImage | null = null; currentImageData: DeckImage | null = null;
// Ändere currentBoxIndex zu boxesToReview als Array
currentBoxIndex: number = 0; currentBoxIndex: number = 0;
boxesToReview: Box[] = []; boxesToReview: Box[] = [];
boxRevealed: boolean[] = []; boxRevealed: boolean[] = [];
knownCount: number = 0;
unknownCount: number = 0;
isShowingBox: boolean = false; isShowingBox: boolean = false;
isTrainingFinished: boolean = false; isTrainingFinished: boolean = false;
constructor(private deckService: DeckService) { } constructor(private deckService: DeckService) { }
ngOnInit(): void { ngOnInit(): void {
// Initialization was done in ngAfterViewInit
} }
ngAfterViewInit(){ ngAfterViewInit() {
// Initialize the first image and its boxes
if (this.deck && this.deck.images.length > 0) { if (this.deck && this.deck.images.length > 0) {
this.loadImage(this.currentImageIndex); this.loadImage(this.currentImageIndex);
} else { } else {
alert('Kein Deck oder keine Bilder vorhanden.'); alert('No deck or images available.');
this.close.emit(); 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 { loadImage(imageIndex: number): void {
if (imageIndex >= this.deck.images.length) { if (imageIndex >= this.deck.images.length) {
this.endTraining(); this.endTraining();
@ -51,13 +64,57 @@ export class TrainingComponent implements OnInit {
} }
this.currentImageData = this.deck.images[imageIndex]; this.currentImageData = this.deck.images[imageIndex];
// Initialisiere boxesToReview mit allen Boxen, gemischt // Initialize the boxes for the current round
this.boxesToReview = this.shuffleArray([...this.currentImageData.boxes]); 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); this.boxRevealed = new Array(this.boxesToReview.length).fill(false);
// Reset the current box index
this.currentBoxIndex = 0;
this.isShowingBox = false; this.isShowingBox = false;
// Redraw the canvas
this.drawCanvas(); 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 { drawCanvas(): void {
const canvas = this.canvasRef.nativeElement; const canvas = this.canvasRef.nativeElement;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
@ -66,51 +123,57 @@ export class TrainingComponent implements OnInit {
const img = new Image(); const img = new Image();
img.src = `/api/debug_image/${this.currentImageData.id}/original_compressed.jpg`; img.src = `/api/debug_image/${this.currentImageData.id}/original_compressed.jpg`;
img.onload = () => { img.onload = () => {
// Set canvas size to image size // Set the canvas size to the image size
canvas.width = img.width; canvas.width = img.width;
canvas.height = img.height; canvas.height = img.height;
// Draw image // Draw the image
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Draw boxes // Draw the boxes
this.boxesToReview.forEach((box, index) => { this.boxesToReview.forEach((box, index) => {
if (this.boxRevealed[index]) {
// Box ist bereits enthüllt, nichts zeichnen
return;
}
ctx.beginPath(); ctx.beginPath();
ctx.rect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1); ctx.rect(box.x1, box.y1, box.x2 - box.x1, box.y2 - box.y1);
ctx.fillStyle = index === this.currentBoxIndex ? 'rgba(0, 255, 0, 0.99)' : 'rgba(255, 0, 0, 0.99)'; 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.fill();
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.strokeStyle = 'black'; ctx.strokeStyle = 'black';
ctx.stroke(); ctx.stroke();
}); });
}; };
img.onerror = () => { img.onerror = () => {
console.error('Fehler beim Laden des Bildes für Canvas.'); console.error('Error loading image for canvas.');
alert('Fehler beim Laden des Bildes für Canvas.'); alert('Error loading image for canvas.');
this.close.emit(); this.close.emit();
}; };
} }
// Utility-Funktion zum Mischen eines Arrays /**
* Shuffles an array randomly.
* @param array The array to shuffle
* @returns The shuffled array
*/
shuffleArray<T>(array: T[]): T[] { shuffleArray<T>(array: T[]): T[] {
let currentIndex = array.length, randomIndex; let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle. // While there are elements to shuffle
while (currentIndex !== 0) { while (currentIndex !== 0) {
// Pick a remaining element
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex); randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--; currentIndex--;
// And swap it with the current element. // Swap it with the current element
[array[currentIndex], array[randomIndex]] = [ [array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]]; array[randomIndex], array[currentIndex]];
} }
@ -118,6 +181,9 @@ export class TrainingComponent implements OnInit {
return array; return array;
} }
/**
* Returns the current box being reviewed.
*/
get currentBox(): Box | null { get currentBox(): Box | null {
if (this.currentBoxIndex < this.boxesToReview.length) { if (this.currentBoxIndex < this.boxesToReview.length) {
return this.boxesToReview[this.currentBoxIndex]; return this.boxesToReview[this.currentBoxIndex];
@ -125,6 +191,9 @@ export class TrainingComponent implements OnInit {
return null; return null;
} }
/**
* Reveals the content of the current box.
*/
showText(): void { showText(): void {
if (this.currentBoxIndex >= this.boxesToReview.length) return; if (this.currentBoxIndex >= this.boxesToReview.length) return;
this.boxRevealed[this.currentBoxIndex] = true; this.boxRevealed[this.currentBoxIndex] = true;
@ -132,67 +201,221 @@ export class TrainingComponent implements OnInit {
this.drawCanvas(); this.drawCanvas();
} }
markKnown(): void { /**
this.knownCount++; * Marks the current box as "Again" and proceeds to the next box.
// Entferne die aktuelle Box aus boxesToReview, da sie bekannt ist */
this.boxesToReview.splice(this.currentBoxIndex, 1); async markAgain(): Promise<void> {
this.boxRevealed.splice(this.currentBoxIndex, 1); await this.updateCard('again');
this.coverCurrentBox();
this.nextBox(); this.nextBox();
} }
markUnknown(): void { /**
this.unknownCount++; * Marks the current box as "Good" and proceeds to the next box.
// Behalte die aktuelle Box in der Liste und verschiebe sie an eine zufällige Position am Ende */
const box = this.boxesToReview.splice(this.currentBoxIndex, 1)[0]; async markGood(): Promise<void> {
this.boxesToReview.push(box); await this.updateCard('good');
this.boxRevealed.splice(this.currentBoxIndex, 1); this.coverCurrentBox();
this.nextBox(); this.nextBox();
} }
nextBox(): void { /**
this.isShowingBox = false; * Marks the current box as "Easy" and proceeds to the next box.
*/
async markEasy(): Promise<void> {
await this.updateCard('easy');
this.coverCurrentBox();
this.nextBox();
}
if (this.boxesToReview.length === 0) { /**
// Alle Boxen für dieses Bild sind bearbeitet * Updates the SRS data of the current box based on the given action.
this.nextImage(); * @param action The action performed ('again', 'good', 'easy')
return; */
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);
alert('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 } {
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;
// Reduce factor but not below minimum
newFactor = Math.max(
FACTOR_CHANGES.MIN,
newFactor * FACTOR_CHANGES.AGAIN
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
} }
if (this.currentBoxIndex >= this.boxesToReview.length) { if (action === 'easy') {
this.currentBoxIndex = 0; newReps++;
newIsGraduated = true;
newIvl = EASY_INTERVAL;
// Increase factor but not above maximum
newFactor = Math.min(
FACTOR_CHANGES.MAX,
newFactor * FACTOR_CHANGES.EASY
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
} }
// Handle 'good' action
newReps++;
if (!newIsGraduated) {
// Card is in learning phase
if (newReps === 1) {
newIvl = LEARNING_STEPS.GOOD;
} else {
// Graduate the card
newIsGraduated = true;
newIvl = LEARNING_STEPS.GRADUATION;
}
} else {
// Card is in review phase, apply space repetition
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(); 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 { nextImage(): void {
this.currentImageIndex++; this.currentImageIndex++;
this.loadImage(this.currentImageIndex); this.loadImage(this.currentImageIndex);
} }
/**
* Skips to the next image in the deck.
*/
skipToNextImage(): void { skipToNextImage(): void {
if (this.currentImageIndex < this.deck.images.length - 1) { if (this.currentImageIndex < this.deck.images.length - 1) {
this.currentImageIndex++; this.currentImageIndex++;
this.loadImage(this.currentImageIndex); this.loadImage(this.currentImageIndex);
} else { } else {
alert('Dies ist das letzte Bild im Deck.'); alert('This is the last image in the deck.');
} }
} }
/**
* Ends the training and displays a completion message.
*/
endTraining(): void { endTraining(): void {
this.isTrainingFinished = true; this.isTrainingFinished = true;
alert(`Training beendet!\nGewusst: ${this.knownCount}\nNicht gewusst: ${this.unknownCount}`); alert(`Training completed!`);
this.close.emit(); this.close.emit();
} }
/**
* Asks the user if they want to end the training and closes it if confirmed.
*/
closeTraining(): void { closeTraining(): void {
if (confirm('Möchtest du das Training wirklich beenden?')) { if (confirm('Do you really want to end the training?')) {
this.close.emit(); this.close.emit();
} }
} }
/**
* Returns the progress of the training, e.g., "Image 2 of 5".
*/
get progress(): string { get progress(): string {
return `Bild ${this.currentImageIndex + 1} von ${this.deck.images.length}`; return `Image ${this.currentImageIndex + 1} of ${this.deck.images.length}`;
} }
} }

View File

@ -1,4 +1,3 @@
<!-- src/app/upload-image-modal.component.html -->
<div #uploadImageModal id="uploadImageModal" 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 #uploadImageModal id="uploadImageModal" 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 h-full contents">
<div class="relative bg-white rounded-lg shadow"> <div class="relative bg-white rounded-lg shadow">
@ -6,29 +5,39 @@
<svg aria-hidden="true" class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <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> <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> </svg>
<span class="sr-only">Schließen</span> <span class="sr-only">Close</span>
</button> </button>
<div class="p-6 relative"> <div class="p-6 relative">
<h3 class="mb-4 text-xl font-medium text-gray-900">Bild zu Deck hinzufügen</h3> <h3 class="mb-4 text-xl font-medium text-gray-900">Add Image to Deck</h3>
<!-- Formular zum Hochladen --> <!-- Upload form -->
<div class="mb-4"> <div class="mb-4">
<label for="imageFile" class="block text-sm font-medium text-gray-700">Bild hochladen</label> <!-- <label for="imageFile" class="block text-sm font-medium text-gray-700">Upload Image</label> -->
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/*" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" /> <!-- <input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/*" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" /> -->
<div class="relative">
<!-- Benutzerdefinierte Schaltfläche und Text -->
<label for="imageFile" class="block w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 cursor-pointer text-center">
Choose File
</label>
<!-- Das eigentliche Datei-Input-Feld -->
<input #imageFile type="file" id="imageFile" (change)="onFileChange($event)" accept="image/*" required class="hidden" />
<!-- Anzeige des ausgewählten Dateinamens -->
<!-- <span id="fileName" class="block mt-2 text-sm text-gray-700 text-center">No file chosen</span> -->
</div>
</div> </div>
<!-- Statusanzeige --> <!-- Status display -->
<div *ngIf="processingStatus" class="mt-4"> <div *ngIf="processingStatus" class="mt-4">
<p class="text-sm text-gray-700">{{ processingStatus }}</p> <p class="text-sm text-gray-700">{{ processingStatus }}</p>
</div> </div>
<!-- Ladeanzeige als Overlay --> <!-- Loading overlay -->
<div *ngIf="loading" class="absolute inset-0 bg-gray-800 bg-opacity-50 flex items-center justify-center z-10"> <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"> <div class="bg-white p-4 rounded shadow">
<p class="text-sm text-gray-700">Verarbeitung läuft...</p> <p class="text-sm text-gray-700">Processing in progress...</p>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,4 +1,3 @@
// src/app/upload-image-modal.component.ts
import { Component, Input, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef, OnDestroy } from '@angular/core'; import { Component, Input, Output, EventEmitter, AfterViewInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import { Box, DeckImage, DeckService, OcrResult } from '../deck.service'; import { Box, DeckImage, DeckService, OcrResult } from '../deck.service';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@ -9,11 +8,20 @@ import { Modal } from 'flowbite';
selector: 'app-upload-image-modal', selector: 'app-upload-image-modal',
templateUrl: './upload-image-modal.component.html', templateUrl: './upload-image-modal.component.html',
standalone: true, standalone: true,
styles:`
label {
transition: background-color 0.3s ease;
}
label:hover {
background-color: #2563eb;
}
`,
imports: [CommonModule] imports: [CommonModule]
}) })
export class UploadImageModalComponent implements AfterViewInit, OnDestroy { export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
@Input() deckName: string = ''; @Input() deckName: string = '';
@Output() imageUploaded = new EventEmitter<{ imageSrc: string | ArrayBuffer | null | undefined, deckImage:DeckImage }>(); @Output() imageUploaded = new EventEmitter<{ imageSrc: string | ArrayBuffer | null | undefined, deckImage: DeckImage }>();
@ViewChild('uploadImageModal') modalElement!: ElementRef; @ViewChild('uploadImageModal') modalElement!: ElementRef;
@ViewChild('imageFile') imageFileElement!: ElementRef; @ViewChild('imageFile') imageFileElement!: ElementRef;
@ -30,7 +38,7 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
} }
ngOnDestroy(): void { ngOnDestroy(): void {
// Modal wird automatisch von Flowbite verwaltet // Modal is automatically managed by Flowbite
} }
open(): void { open(): void {
@ -51,63 +59,68 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
onFileChange(event: any): void { onFileChange(event: any): void {
const file: File = event.target.files[0]; const file: File = event.target.files[0];
if (!file) return; if (!file) return;
const fileNameElement = document.getElementById('fileName');
if (fileNameElement) {
fileNameElement.textContent = file.name;
}
this.imageFile = file; this.imageFile = file;
this.processingStatus = 'Verarbeitung läuft...'; this.processingStatus = 'Processing in progress...';
this.loading = true; this.loading = true;
const reader = new FileReader(); const reader = new FileReader();
reader.onload = async (e) => { reader.onload = async (e) => {
const imageSrc = e.target?.result; const imageSrc = e.target?.result;
// Bild als Base64-String ohne Präfix (data:image/...) // Image as Base64 string without prefix (data:image/...)
const imageBase64 = (imageSrc as string).split(',')[1]; const imageBase64 = (imageSrc as string).split(',')[1];
try { try {
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise(); const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
if (!response || !response.results) { if (!response || !response.results) {
this.processingStatus = 'Ungültige Antwort vom OCR-Service'; this.processingStatus = 'Invalid response from OCR service';
this.loading = false; this.loading = false;
return; return;
} }
this.processingStatus = 'Verarbeitung abgeschlossen'; this.processingStatus = 'Processing complete';
this.loading = false; this.loading = false;
// Emit Event mit Bilddaten und OCR-Ergebnissen // Emit event with image data and OCR results
const bildname=this.imageFile?.name??''; const imageName = this.imageFile?.name ?? '';
const bildid=response.results.length>0?response.results[0].name:null const imageId = response.results.length > 0 ? response.results[0].name : null;
const boxes:Box[] = []; const boxes: Box[] = [];
response.results.forEach((result: OcrResult) => { response.results.forEach((result: OcrResult) => {
const box = result.box; const box = result.box;
const xs = box.map((point: number[]) => point[0]); const xs = box.map((point: number[]) => point[0]);
const ys = box.map((point: number[]) => point[1]); const ys = box.map((point: number[]) => point[1]);
const xMin = Math.min(...xs); const xMin = Math.min(...xs);
const xMax = Math.max(...xs); const xMax = Math.max(...xs);
const yMin = Math.min(...ys); const yMin = Math.min(...ys);
const yMax = Math.max(...ys); const yMax = Math.max(...ys);
boxes.push({x1:xMin,x2:xMax,y1:yMin,y2:yMax}) boxes.push({ x1: xMin, x2: xMax, y1: yMin, y2: yMax });
}); });
const deckImage:DeckImage={name:bildname,id:bildid,boxes} const deckImage: DeckImage = { name: imageName, id: imageId, boxes };
this.imageUploaded.emit({ imageSrc, deckImage }); this.imageUploaded.emit({ imageSrc, deckImage });
this.resetFileInput(); this.resetFileInput();
// Schließe das Upload-Modal // Close the upload modal
this.closeModal(); this.closeModal();
} catch (error) { } catch (error) {
console.error('Fehler beim OCR-Service:', error); console.error('Error with OCR service:', error);
this.processingStatus = 'Fehler beim OCR-Service'; this.processingStatus = 'Error with OCR service';
this.loading = false; this.loading = false;
} }
}; };
reader.readAsDataURL(file); reader.readAsDataURL(file);
} }
/** /**
* Setzt das Datei-Input-Feld zurück, sodass dieselbe Datei erneut ausgewählt werden kann. * Resets the file input field so the same file can be selected again.
*/ */
resetFileInput(): void { resetFileInput(): void {
if (this.imageFileElement && this.imageFileElement.nativeElement) { if (this.imageFileElement && this.imageFileElement.nativeElement) {
this.imageFileElement.nativeElement.value = ''; this.imageFileElement.nativeElement.value = '';
} }
} }
} }