Compare commits

...

5 Commits

Author SHA1 Message Date
303ba7c4b2 bugfixes 2025-01-16 18:26:12 +00:00
0ea427b265 small changes 2025-01-16 10:38:59 +00:00
ddac7102fe responsive part 1, new orientation 2025-01-16 00:07:10 +00:00
49c1185372 rename&delete Deck, popover 2025-01-15 21:38:38 +00:00
f968f2ab38 translate to english 2025-01-15 00:05:57 +00:00
14 changed files with 559 additions and 371 deletions

View File

@@ -1,14 +1,13 @@
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { initFlowbite } from 'flowbite';
import { DeckListComponent } from './deck-list.component';
@Component({
selector: 'app-root',
template: `
<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>
</div>
`,
@@ -16,8 +15,7 @@ import { DeckListComponent } from './deck-list.component';
imports: [CommonModule, DeckListComponent]
})
export class AppComponent {
title = 'vokabeltraining';
title = 'vocabulary-training';
ngOnInit(): void {
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 class="relative w-full h-full max-w-md md:h-auto">
<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">
<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">Schließen</span>
<span class="sr-only">Close</span>
</button>
<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)">
<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" />
</div>
<button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Erstellen
Create
</button>
</form>
</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 { DeckService } from '../deck.service';
import { CommonModule } from '@angular/common';
@@ -30,7 +29,7 @@ export class CreateDeckModalComponent implements AfterViewInit {
createDeck(event: Event): void {
event.preventDefault();
if (this.deckName.trim() === '') {
alert('Bitte einen Deck-Namen eingeben.');
alert('Please enter a deck name.');
return;
}
@@ -41,8 +40,8 @@ export class CreateDeckModalComponent implements AfterViewInit {
this.modal.hide();
},
error: (err) => {
console.error('Fehler beim Erstellen des Decks', err);
alert('Fehler beim Erstellen des Decks.');
console.error('Error creating deck', err);
alert('Error creating deck.');
}
});
}
@@ -51,4 +50,3 @@ export class CreateDeckModalComponent implements AfterViewInit {
this.modal.hide();
}
}

View File

@@ -1,64 +1,88 @@
<!-- src/app/deck-list.component.html -->
<div>
<!-- Button zum Erstellen eines neuen Decks -->
<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">
Neues Deck erstellen
<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 items-center space-x-2 whitespace-nowrap">
<h3 class="font-medium">{{ deck.name }}</h3>
<span class="text-gray-600">({{ deck.images.length }})</span>
</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>
<!-- Decks anzeigen -->
<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 border-dashed border-2 border-indigo-600">
<!-- Deck-Header mit Toggle-Button -->
<!-- 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">{{ deck.name }}</h2>
<span class="text-gray-600">({{ deck.images.length }} Bilder)</span>
</div>
<button (click)="toggleDeckExpansion(deck.name)" class="text-gray-500 hover:text-gray-700 focus:outline-none" title="Deck ein-/ausklappen">
<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" />
</svg>
<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" />
</svg>
</button>
</div>
<!-- Bildliste und Action-Buttons nur anzeigen, wenn das Deck erweitert ist und kein Training aktiv ist -->
<ng-container *ngIf="isDeckExpanded(deck.name) && !selectedDeck">
<!-- Liste der Bilder mit Anzahl der Boxen und Icons -->
<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">
<div class="flex items-center space-x-2">
<div class="relative group">
<!-- Tooltip Inhalt (Bild) -->
<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">
</div>
<!-- Bildname mit Tooltip -->
<span class="font-medium cursor-pointer">
{{ image.name }}
</span>
</div>
<span class="text-gray-600">({{ image.boxes.length }} Boxen)</span>
<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">
<!-- Edit Icon -->
<button (click)="editImage(deck, image)" class="text-blue-500 hover:text-blue-700" title="Bild bearbeiten">
<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>
<!-- Delete Icon -->
<button (click)="deleteImage(deck, image)" class="text-red-500 hover:text-red-700" title="Bild löschen">
<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>
<!-- Move Icon -->
<button (click)="openMoveImageModal(deck, image)" class="text-yellow-500 hover:text-yellow-700" title="Bild verschieben">
<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="/api/debug_image/{{image.id}}/thumbnail.jpg" 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>
@@ -67,28 +91,26 @@
</li>
</ul>
<!-- Action-Buttons -->
<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">
Training starten
<!-- Action buttons -->
<div class="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-2">
<button (click)="openTraining(activeDeck)" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Start Training
</button>
<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
<button (click)="openUploadImageModal(activeDeck.name)" class="flex-1 bg-green-500 text-white py-2 px-4 rounded hover:bg-green-600">
Add Image
</button>
</div>
</ng-container>
</div>
</div>
</div>
<!-- CreateDeckModalComponent -->
<app-create-deck-modal (deckCreated)="loadDecks()"></app-create-deck-modal>
<!-- 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-edit-image-modal *ngIf="imageData" [deckName]="currentUploadDeckName" [imageData]="imageData" (imageSaved)="onImageSaved()" (closed)="onClosed()"></app-edit-image-modal>
<!-- TrainingComponent -->
<app-training *ngIf="selectedDeck" [deck]="selectedDeck" (close)="closeTraining()"></app-training>
<app-training *ngIf="trainingsDeck" [deck]="trainingsDeck" (close)="closeTraining()"></app-training>
<!-- MoveImageModalComponent -->
<app-move-image-modal
*ngIf="imageToMove"
@@ -99,3 +121,21 @@
(closed)="imageToMove = null">
</app-move-image-modal>
</div>
<!-- Popover für die Löschbestätigung -->
<div id="deletePopover" popover="manual" class="popover">
<p>Are you sure you want to delete this deck?</p>
<div class="flex justify-end space-x-2">
<button (click)="confirmDelete()" class="bg-red-500 text-white px-4 py-2 rounded">Delete</button>
<button (click)="cancelDelete()" class="bg-gray-500 text-white px-4 py-2 rounded">Cancel</button>
</div>
</div>
<!-- Popover für die Eingabe des neuen Decknamens -->
<div id="renamePopover" popover="manual" class="popover">
<p>Enter the new name for the deck:</p>
<input type="text" id="newDeckNameInput" class="w-full p-2 border rounded mb-2" [value]="deckToRename?.name" />
<div class="flex justify-end space-x-2">
<button (click)="confirmRename()" class="bg-blue-500 text-white px-4 py-2 rounded">Rename</button>
<button (click)="cancelRename()" class="bg-gray-500 text-white px-4 py-2 rounded">Cancel</button>
</div>
</div>

View File

@@ -1,4 +1,3 @@
// src/app/deck-list.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { DeckService, Deck, DeckImage } from './deck.service';
import { CommonModule } from '@angular/common';
@@ -13,19 +12,32 @@ import { MoveImageModalComponent } from './move-image-modal/move-image-modal.com
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,
UploadImageModalComponent,
TrainingComponent,
EditImageModalComponent,
MoveImageModalComponent, // Hinzufügen der neuen Komponente
MoveImageModalComponent, // Adding the new component
UploadImageModalComponent
]
})
export class DeckListComponent implements OnInit {
decks: Deck[] = [];
selectedDeck: Deck | null = null;
trainingsDeck: Deck | null = null;
activeDeck: Deck | null = null;
private deckToDelete: string | null = null;
deckToRename: Deck | null = null;
@ViewChild(CreateDeckModalComponent) createDeckModal!: CreateDeckModalComponent;
@ViewChild(UploadImageModalComponent) uploadImageModal!: UploadImageModalComponent;
@@ -36,10 +48,10 @@ export class DeckListComponent implements OnInit {
currentUploadDeckName: string = '';
// Set zur Verfolgung erweiterter Decks
// Set to track expanded decks
expandedDecks: Set<string> = new Set<string>();
// State für das Verschieben von Bildern
// State for moving images
imageToMove: { image: DeckImage, sourceDeck: Deck } | null = null;
constructor(private deckService: DeckService) { }
@@ -51,23 +63,141 @@ export class DeckListComponent implements OnInit {
loadDecks(): void {
this.deckService.getDecks().subscribe({
next: (data) => this.decks = data,
error: (err) => console.error('Fehler beim Laden der Decks', err)
next: (data) => {
this.decks = data;
// Set the first deck as active if none is selected
if (!this.activeDeck && this.decks.length > 0) {
this.activeDeck = this.decks[0];
}
},
error: (err) => console.error('Error loading decks', err)
});
}
// Updated toggle method
toggleDeckExpansion(deck: Deck): void {
this.activeDeck = deck;
}
// Method to open the delete confirmation popover
openDeletePopover(deckName: string): void {
this.deckToDelete = deckName;
const deletePopover = document.getElementById('deletePopover');
if (deletePopover) {
deletePopover.showPopover();
}
}
// 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(): void {
if (this.deckToDelete) {
this.deckService.deleteDeck(this.deckToDelete).subscribe({
next: () => {
this.loadDecks();
this.closeDeletePopover();
this.activeDeck = this.decks[0];
},
error: (err) => console.error('Error deleting deck', err),
});
}
}
// Method to cancel the deletion of a deck
cancelDelete(): void {
this.closeDeletePopover();
}
// Method to close the delete confirmation popover
closeDeletePopover(): void {
const deletePopover = document.getElementById('deletePopover');
if (deletePopover) {
deletePopover.hidePopover();
}
this.deckToDelete = null;
}
// Method to open the rename popover
openRenamePopover(deck: Deck): void {
this.deckToRename = deck;
const renamePopover = document.getElementById('renamePopover');
if (renamePopover) {
renamePopover.showPopover();
// Set the input value to the current deck name and select it
setTimeout(() => {
const newDeckNameInput = document.getElementById('newDeckNameInput') as HTMLInputElement;
if (newDeckNameInput) {
newDeckNameInput.value = deck.name;
newDeckNameInput.select();
}
}, 0);
}
}
// Method to confirm the renaming of a deck
confirmRename(): void {
const newDeckNameInput = document.getElementById('newDeckNameInput') as HTMLInputElement;
if (newDeckNameInput && this.deckToRename) {
const newDeckName = newDeckNameInput.value.trim();
if (newDeckName && newDeckName !== this.deckToRename.name) {
this.deckService.renameDeck(this.deckToRename.name, newDeckName).subscribe({
next: () => {
// Aktualisiere den Namen im activeDeck, falls dieser der umbenannte Deck ist
if (this.activeDeck && this.activeDeck.name === this.deckToRename?.name) {
this.activeDeck.name = newDeckName;
}
this.loadDecks(); // Lade die Decks neu, um die Liste zu aktualisieren
this.closeRenamePopover();
},
error: (err) => console.error('Error renaming deck', err),
});
}
}
}
// Method to cancel the renaming of a deck
cancelRename(): void {
this.closeRenamePopover();
}
// Method to close the rename popover
closeRenamePopover(): void {
const renamePopover = document.getElementById('renamePopover');
if (renamePopover) {
renamePopover.hidePopover();
}
this.deckToRename = null;
}
// Method to delete a deck
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;
}
this.deckService.deleteDeck(deckName).subscribe({
next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Decks', err)
error: (err) => console.error('Error deleting deck', err)
});
}
// Method to rename a deck
renameDeck(deck: Deck): void {
const newDeckName = prompt('Enter the new name for the deck:', deck.name);
if (newDeckName && newDeckName !== deck.name) {
this.deckService.renameDeck(deck.name, newDeckName).subscribe({
next: () => this.loadDecks(),
error: (err) => console.error('Error renaming deck', err)
});
}
}
// Method to delete an image from a deck
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;
}
@@ -75,68 +205,63 @@ export class DeckListComponent implements OnInit {
this.deckService.deleteImage(imageId).subscribe({
next: () => this.loadDecks(),
error: (err) => console.error('Fehler beim Löschen des Bildes', err)
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
let imageSrc = null;
this.currentUploadDeckName = deck.name;
fetch(`/api/debug_image/${image.id}/original_compressed.jpg`)
.then(response => {
if (!response.ok) {
throw new Error('Netzwerkantwort war nicht 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 }
imageSrc = reader.result; // Base64 string
this.imageData = { imageSrc, deckImage: image };
};
reader.readAsDataURL(blob);
})
.catch(error => {
console.error('Fehler beim Laden des Bildes:', error);
console.error('Error loading image:', error);
});
}
// Method to open the training component
openTraining(deck: Deck): void {
this.selectedDeck = deck;
this.trainingsDeck = deck;
}
// Method to close the training component
closeTraining(): void {
this.selectedDeck = null;
this.trainingsDeck = null;
this.loadDecks();
}
// Method to open the create deck modal
openCreateDeckModal(): void {
this.createDeckModal.open();
}
// Method to open the upload image modal
openUploadImageModal(deckName: string): void {
this.currentUploadDeckName = deckName;
this.uploadImageModal.deckName = deckName;
this.uploadImageModal.open();
}
// Methode zum Umschalten der Deck-Erweiterung
toggleDeckExpansion(deckName: string): void {
if (this.expandedDecks.has(deckName)) {
this.expandedDecks.delete(deckName);
} else {
this.expandedDecks.add(deckName);
}
this.saveExpandedDecks();
}
// Methode zur Überprüfung, ob ein Deck erweitert ist
// Method to check if a deck is expanded
isDeckExpanded(deckName: string): boolean {
return this.expandedDecks.has(deckName);
}
// Laden der erweiterten Decks aus dem sessionStorage
// Method to load expanded decks from sessionStorage
loadExpandedDecks(): void {
const stored = sessionStorage.getItem('expandedDecks');
if (stored) {
@@ -144,26 +269,26 @@ export class DeckListComponent implements OnInit {
const parsed: string[] = JSON.parse(stored);
this.expandedDecks = new Set<string>(parsed);
} catch (e) {
console.error('Fehler beim Parsen der erweiterten Decks aus sessionStorage', e);
console.error('Error parsing expanded decks from sessionStorage', e);
}
} 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<string>();
}
}
// Speichern der erweiterten Decks in das sessionStorage
// Method to save expanded decks to sessionStorage
saveExpandedDecks(): void {
const expandedArray = Array.from(this.expandedDecks);
sessionStorage.setItem('expandedDecks', JSON.stringify(expandedArray));
}
// Funktion zum Öffnen des Upload Modals (kann durch einen Button ausgelöst werden)
// Method to open the upload modal
openUploadModal(): void {
this.uploadImageModal.open();
}
// Handler für das imageUploaded Event
// Handler for the imageUploaded event
onImageUploaded(imageData: any): void {
this.imageData = imageData;
}
@@ -173,17 +298,27 @@ export class DeckListComponent implements OnInit {
}
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.decks = await firstValueFrom(this.deckService.getDecks())
// 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;
}
}
}
// Methode zum Öffnen des MoveImageModal
// Method to open the MoveImageModal
openMoveImageModal(deck: Deck, image: DeckImage): void {
this.imageToMove = { image, sourceDeck: deck };
}
// Handler für das moveCompleted Event
// Handler for the moveCompleted event
onImageMoved(): void {
this.imageToMove = null;
this.loadDecks();

View File

@@ -1,4 +1,3 @@
// src/app/deck.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, Observable, switchMap } from 'rxjs';
@@ -39,13 +38,13 @@ export interface BackendBox {
y2: number;
}
// Definiert ein einzelnes Punktpaar [x, y]
// Defines a single point pair [x, y]
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];
// Interface für jedes JSON-Objekt
// Interface for each JSON object
export interface OcrResult {
box: OcrBox;
confidence: number;
@@ -69,6 +68,7 @@ export class DeckService {
})))
);
}
private groupImagesByName(images: any[]): DeckImage[] {
const imageMap: { [key: string]: DeckImage } = {};
@@ -97,6 +97,7 @@ export class DeckService {
return Object.values(imageMap);
}
getDeck(deckname: string): Observable<Deck> {
return this.http.get<Deck>(`${this.apiUrl}/${deckname}/images`);
}
@@ -108,17 +109,19 @@ export class DeckService {
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 });
}
saveImageData(data: any): Observable<any> {
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> {
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> {
return this.http.post(`${this.apiUrl}/images/${imageId}/move`, { targetDeckId });
}

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 class="relative h-full contents">
<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">
<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">Schließen</span>
<span class="sr-only">Close</span>
</button>
<div class="p-6 relative">
<!-- Überschrift mit Boxanzahl -->
<!-- Header with box count -->
<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>
<!-- Canvas -->
@@ -19,13 +18,13 @@
<canvas #canvas class="border border-gray-300 rounded w-full h-auto"></canvas>
</div>
<!-- Buttons unter dem Canvas -->
<!-- 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">
Neue Box
New Box
</button>
</div>
</div>

View File

@@ -12,8 +12,8 @@ import { DeckImage, DeckService, OcrResult } from '../deck.service';
imports: [CommonModule]
})
export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// Konstante für die Boxfarbe
private readonly BOX_COLOR = 'rgba(255, 0, 0, 0.3)'; // Rot mit Transparenz
// 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 };
@@ -38,8 +38,8 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.modal = new Modal(this.modalElement.nativeElement, {
onHide: () => {
this.closed.emit();
}},
);
}
});
this.maxCanvasWidth = window.innerWidth * 0.6;
this.maxCanvasHeight = window.innerHeight * 0.6;
@@ -95,7 +95,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.canvas = new fabric.Canvas(this.canvasElement.nativeElement);
// Hintergrundbild setzen
// Set background image
const backgroundImage = await this.loadFabricImage(this.imageData.imageSrc as string);
const originalWidth = backgroundImage.width!;
@@ -120,7 +120,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.boxes = [];
// Boxen hinzufügen
// Add boxes
this.imageData.deckImage?.boxes.forEach(box => {
const rect = new fabric.Rect({
@@ -128,7 +128,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
top: box.y1 * scaleFactor,
width: (box.x2 - box.x1) * scaleFactor,
height: (box.y2 - box.y1) * scaleFactor,
fill: this.BOX_COLOR, // Verwendung der Konstante
fill: this.BOX_COLOR, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
@@ -159,7 +159,7 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
// this.detectedText = ocrResults.map(result => result.text).join('\n');
} 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,
width: boxWidth,
height: boxHeight,
fill: this.BOX_COLOR, // Verwendung der Konstante
fill: this.BOX_COLOR, // Use the constant
selectable: true,
hasControls: true,
hasBorders: true,
@@ -252,8 +252,8 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
}
save(): void {
// Hier implementierst du die Logik zum Speichern der Bilddaten
// Zum Beispiel über einen Service oder direkt hier
// 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,
@@ -266,8 +266,8 @@ export class EditImageModalComponent implements AfterViewInit, OnDestroy {
this.closeModal();
},
error: (err) => {
console.error('Fehler beim Speichern des Bildes:', err);
alert('Fehler beim Speichern des Bildes.');
console.error('Error saving image:', err);
alert('Error saving image.');
this.closeModal();
}
});

View File

@@ -1,8 +1,7 @@
<!-- 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="bg-white rounded-lg shadow-lg w-96 p-6">
<h2 class="text-xl font-semibold mb-4">Bild verschieben</h2>
<p class="mb-4">Wähle das Zieldeck für das Bild <strong>{{ image.name }}</strong> aus.</p>
<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 }}
@@ -10,15 +9,14 @@
</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">
Abbrechen
Cancel
</button>
<button
(click)="moveImage()"
[disabled]="!selectedDeckId"
class="bg-yellow-500 text-white py-2 px-4 rounded hover:bg-yellow-600">
Verschieben
Move
</button>
</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 { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DeckImage, Deck, DeckService } from '../deck.service';
@@ -33,8 +31,8 @@ export class MoveImageModalComponent {
this.close();
},
error: (err) => {
console.error('Fehler beim Verschieben des Bildes:', err);
alert('Fehler beim Verschieben des Bildes.');
console.error('Error moving image:', err);
alert('Error moving image.');
}
});
}

View File

@@ -1,53 +1,52 @@
<!-- src/app/training.component.html -->
<div class="mt-10">
<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">
<canvas #canvas class="mb-4 border max-h-[50vh]"></canvas>
<div class="flex space-x-4 mb-4">
<!-- Anzeigen Button -->
<!-- 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"
>
Anzeigen
Show
</button>
<!-- Nochmal 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"
>
Nochmal ({{ getNextInterval(currentBox, 'again') }})
Again ({{ getNextInterval(currentBox, 'again') }})
</button>
<!-- Gut 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"
>
Gut ({{ getNextInterval(currentBox, 'good') }})
Good ({{ getNextInterval(currentBox, 'good') }})
</button>
<!-- Einfach 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"
>
Einfach ({{ getNextInterval(currentBox, 'easy') }})
Easy ({{ getNextInterval(currentBox, 'easy') }})
</button>
<!-- Nächstes Bild 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"
>
Nächstes Bild
Next Image
</button>
</div>
@@ -57,7 +56,7 @@
(click)="closeTraining()"
class="mt-4 text-gray-500 hover:text-gray-700 underline"
>
Training beenden
End Training
</button>
</div>
</div>

View File

@@ -1,4 +1,3 @@
// training.component.ts
import { Component, Input, Output, EventEmitter, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Deck, DeckImage, DeckService, Box } from '../deck.service';
import { CommonModule } from '@angular/common';
@@ -41,22 +40,22 @@ export class TrainingComponent implements OnInit {
constructor(private deckService: DeckService) { }
ngOnInit(): void {
// Initialisierung wurde in ngAfterViewInit durchgeführt
// Initialization was done in ngAfterViewInit
}
ngAfterViewInit() {
// Initialisiere das erste Bild und die dazugehörigen Boxen
// Initialize the first image and its boxes
if (this.deck && this.deck.images.length > 0) {
this.loadImage(this.currentImageIndex);
} else {
alert('Kein Deck oder keine Bilder vorhanden.');
alert('No deck or images available.');
this.close.emit();
}
}
/**
* Lädt das Bild basierend auf dem gegebenen Index und initialisiert die zu überprüfenden Boxen.
* @param imageIndex Index des zu ladenden Bildes im Deck
* 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) {
@@ -65,13 +64,13 @@ export class TrainingComponent implements OnInit {
}
this.currentImageData = this.deck.images[imageIndex];
// Initialisiere die Boxen für die aktuelle Runde
// Initialize the boxes for the current round
this.initializeBoxesToReview();
}
/**
* Ermittelt alle fälligen Boxen für die aktuelle Runde, mischt sie und setzt den aktuellen Box-Index zurück.
* Wenn keine Boxen mehr zu überprüfen sind, wird zum nächsten Bild gewechselt.
* 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) {
@@ -79,42 +78,42 @@ export class TrainingComponent implements OnInit {
return;
}
// Filtere alle Boxen, die fällig sind (due <= heute)
// 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) {
// Keine Boxen mehr für dieses Bild, wechsle zum nächsten Bild
// No more boxes for this image, move to the next image
this.nextImage();
return;
}
// Mische die Boxen zufällig
// Shuffle the boxes randomly
this.boxesToReview = this.shuffleArray(this.boxesToReview);
// Initialisiere den Array zur Verfolgung der enthüllten Boxen
// Initialize the array to track revealed boxes
this.boxRevealed = new Array(this.boxesToReview.length).fill(false);
// Setze den aktuellen Box-Index zurück
// Reset the current box index
this.currentBoxIndex = 0;
this.isShowingBox = false;
// Zeichne das Canvas neu
// Redraw the canvas
this.drawCanvas();
}
/**
* Gibt das heutige Datum in Tagen seit der UNIX-Epoche zurück.
* Returns today's date in days since the UNIX epoch.
*/
getTodayInDays(): number {
const epoch = new Date(1970, 0, 1); // Anki verwendet UNIX-Epoche
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));
}
/**
* Zeichnet das aktuelle Bild und die Boxen auf das Canvas.
* Boxen werden rot dargestellt, wenn sie verdeckt sind, und grün, wenn sie enthüllt sind.
* 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;
@@ -124,27 +123,27 @@ export class TrainingComponent implements OnInit {
const img = new Image();
img.src = `/api/debug_image/${this.currentImageData.id}/original_compressed.jpg`;
img.onload = () => {
// Setze die Größe des Canvas auf die Größe des Bildes
// Set the canvas size to the image size
canvas.width = img.width;
canvas.height = img.height;
// Zeichne das Bild
// Draw the image
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Zeichne die Boxen
// 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 ist aktuell enthüllt, keine Überlagerung
// Box is currently revealed, no overlay
return;
} else if (this.currentBoxIndex === index && !this.isShowingBox) {
// Box ist enthüllt
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Undurchsichtige grüne Überlagerung
// Box is revealed
ctx.fillStyle = 'rgba(0, 255, 0, 1)'; // Opaque green overlay
} else {
// Box ist verdeckt
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Undurchsichtige rote Überlagerung
// Box is hidden
ctx.fillStyle = 'rgba(255, 0, 0, 1)'; // Opaque red overlay
}
ctx.fill();
ctx.lineWidth = 2;
@@ -154,27 +153,27 @@ export class TrainingComponent implements OnInit {
};
img.onerror = () => {
console.error('Fehler beim Laden des Bildes für Canvas.');
alert('Fehler beim Laden des Bildes für Canvas.');
console.error('Error loading image for canvas.');
alert('Error loading image for canvas.');
this.close.emit();
};
}
/**
* Mischt ein Array zufällig.
* @param array Das zu mischende Array
* @returns Das gemischte Array
* Shuffles an array randomly.
* @param array The array to shuffle
* @returns The shuffled array
*/
shuffleArray<T>(array: T[]): T[] {
let currentIndex = array.length, randomIndex;
// Solange noch Elemente zum Mischen vorhanden sind
// While there are elements to shuffle
while (currentIndex !== 0) {
// Wähle ein verbleibendes Element
// Pick a remaining element
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// Tausche es mit dem aktuellen Element
// Swap it with the current element
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
@@ -183,7 +182,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Gibt die aktuelle Box zurück, die überprüft wird.
* Returns the current box being reviewed.
*/
get currentBox(): Box | null {
if (this.currentBoxIndex < this.boxesToReview.length) {
@@ -193,7 +192,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Zeigt den Inhalt der aktuellen Box an.
* Reveals the content of the current box.
*/
showText(): void {
if (this.currentBoxIndex >= this.boxesToReview.length) return;
@@ -203,7 +202,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Nochmal" und fährt mit der nächsten Box fort.
* Marks the current box as "Again" and proceeds to the next box.
*/
async markAgain(): Promise<void> {
await this.updateCard('again');
@@ -212,7 +211,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Gut" und fährt mit der nächsten Box fort.
* Marks the current box as "Good" and proceeds to the next box.
*/
async markGood(): Promise<void> {
await this.updateCard('good');
@@ -221,7 +220,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Markiert die aktuelle Box als "Einfach" und fährt mit der nächsten Box fort.
* Marks the current box as "Easy" and proceeds to the next box.
*/
async markEasy(): Promise<void> {
await this.updateCard('easy');
@@ -230,8 +229,8 @@ export class TrainingComponent implements OnInit {
}
/**
* Aktualisiert die SRS-Daten der aktuellen Box basierend auf der gegebenen Aktion.
* @param action Die durchgeführte Aktion ('again', 'good', 'easy')
* 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;
@@ -239,41 +238,41 @@ export class TrainingComponent implements OnInit {
const box = this.boxesToReview[this.currentBoxIndex];
const today = this.getTodayInDays();
// Berechne das neue Intervall und eventuell den neuen Faktor
// Calculate the new interval and possibly the new factor
const { newIvl, newFactor, newReps, newLapses, newIsGraduated } = this.calculateNewInterval(box, action);
// Aktualisiere das Fälligkeitsdatum
// Update the due date
const nextDue = today + Math.floor(newIvl / 1440);
// Aktualisiere das Box-Objekt
// Update the box object
box.ivl = newIvl;
box.factor = newFactor;
box.reps = newReps;
box.lapses = newLapses;
box.due = nextDue;
box.isGraduated = newIsGraduated
box.isGraduated = newIsGraduated;
// Sende das Update an das Backend
// Send the update to the backend
try {
await lastValueFrom(this.deckService.updateBox(box));
} catch (error) {
console.error('Fehler beim Aktualisieren der Box:', error);
alert('Fehler beim Aktualisieren der Box.');
console.error('Error updating box:', error);
alert('Error updating box.');
}
}
/**
* Berechnet das neue Intervall, den Faktor, die Wiederholungen und die Lapses basierend auf der Aktion.
* @param box Die aktuelle Box
* @param action Die Aktion ('again', 'good', 'easy')
* @returns Ein Objekt mit den neuen Werten für ivl, factor, reps und lapses
* 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
let newIsGraduated = box.isGraduated || false;
if (action === 'again') {
newLapses++;
@@ -301,7 +300,7 @@ export class TrainingComponent implements OnInit {
newFactor * FACTOR_CHANGES.EASY
);
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };;
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
// Handle 'good' action
@@ -321,14 +320,14 @@ export class TrainingComponent implements OnInit {
newIvl = Math.round(newIvl * newFactor);
}
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };;
return { newIvl, newFactor, newReps, newLapses, newIsGraduated };
}
/**
* Berechnet das nächste Intervall basierend auf der Aktion und gibt es als String zurück.
* @param box Die aktuelle Box
* @param action Die Aktion ('again', 'good', 'easy')
* @returns Das nächste Intervall als String (z.B. "10 min", "2 d")
* 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)
@@ -340,9 +339,9 @@ export class TrainingComponent implements OnInit {
}
/**
* Formatiert das Intervall als String, entweder in Minuten oder Tagen.
* @param ivl Das Intervall in Tagen
* @returns Das formatierte Intervall als String
* 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`;
@@ -351,7 +350,7 @@ export class TrainingComponent implements OnInit {
}
/**
* Deckt die aktuelle Box wieder auf (verdeckt sie erneut).
* Covers the current box again (hides it).
*/
coverCurrentBox(): void {
this.boxRevealed[this.currentBoxIndex] = false;
@@ -359,24 +358,24 @@ export class TrainingComponent implements OnInit {
}
/**
* Geht zur nächsten Box. Wenn alle Boxen in der aktuellen Runde bearbeitet wurden,
* wird eine neue Runde gestartet.
* 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) {
// Runde abgeschlossen, starte eine neue Runde
// Round completed, start a new round
this.initializeBoxesToReview();
} else {
// Gehe zur nächsten Box
// Move to the next box
this.currentBoxIndex++;
this.drawCanvas();
}
}
/**
* Wechselt zum nächsten Bild im Deck.
* Moves to the next image in the deck.
*/
nextImage(): void {
this.currentImageIndex++;
@@ -384,39 +383,39 @@ export class TrainingComponent implements OnInit {
}
/**
* Überspringt zum nächsten Bild im Deck.
* 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 {
alert('Dies ist das letzte Bild im Deck.');
alert('This is the last image in the deck.');
}
}
/**
* Beendet das Training und gibt eine Abschlussmeldung aus.
* Ends the training and displays a completion message.
*/
endTraining(): void {
this.isTrainingFinished = true;
alert(`Training beendet!`);
alert(`Training completed!`);
this.close.emit();
}
/**
* Fragt den Benutzer, ob das Training beendet werden soll, und schließt es gegebenenfalls.
* Asks the user if they want to end the training and closes it if confirmed.
*/
closeTraining(): void {
if (confirm('Möchtest du das Training wirklich beenden?')) {
if (confirm('Do you really want to end the training?')) {
this.close.emit();
}
}
/**
* Gibt den Fortschritt des Trainings an, z.B. "Bild 2 von 5".
* Returns the progress of the training, e.g., "Image 2 of 5".
*/
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 class="relative h-full contents">
<div class="relative bg-white rounded-lg shadow">
@@ -6,26 +5,36 @@
<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">Schließen</span>
<span class="sr-only">Close</span>
</button>
<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">
<label for="imageFile" class="block text-sm font-medium text-gray-700">Bild hochladen</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" />
<!-- <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" /> -->
<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>
<!-- Statusanzeige -->
<!-- Status display -->
<div *ngIf="processingStatus" class="mt-4">
<p class="text-sm text-gray-700">{{ processingStatus }}</p>
</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 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>

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 { Box, DeckImage, DeckService, OcrResult } from '../deck.service';
import { CommonModule } from '@angular/common';
@@ -9,6 +8,15 @@ import { Modal } from 'flowbite';
selector: 'app-upload-image-modal',
templateUrl: './upload-image-modal.component.html',
standalone: true,
styles:`
label {
transition: background-color 0.3s ease;
}
label:hover {
background-color: #2563eb;
}
`,
imports: [CommonModule]
})
export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
@@ -30,7 +38,7 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
}
ngOnDestroy(): void {
// Modal wird automatisch von Flowbite verwaltet
// Modal is automatically managed by Flowbite
}
open(): void {
@@ -51,32 +59,36 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
onFileChange(event: any): void {
const file: File = event.target.files[0];
if (!file) return;
const fileNameElement = document.getElementById('fileName');
if (fileNameElement) {
fileNameElement.textContent = file.name;
}
this.imageFile = file;
this.processingStatus = 'Verarbeitung läuft...';
this.processingStatus = 'Processing in progress...';
this.loading = true;
const reader = new FileReader();
reader.onload = async (e) => {
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];
try {
const response = await this.http.post<any>('/api/ocr', { image: imageBase64 }).toPromise();
if (!response || !response.results) {
this.processingStatus = 'Ungültige Antwort vom OCR-Service';
this.processingStatus = 'Invalid response from OCR service';
this.loading = false;
return;
}
this.processingStatus = 'Verarbeitung abgeschlossen';
this.processingStatus = 'Processing complete';
this.loading = false;
// Emit Event mit Bilddaten und OCR-Ergebnissen
const bildname=this.imageFile?.name??'';
const bildid=response.results.length>0?response.results[0].name:null
// Emit event with image data and OCR results
const imageName = this.imageFile?.name ?? '';
const imageId = response.results.length > 0 ? response.results[0].name : null;
const boxes: Box[] = [];
response.results.forEach((result: OcrResult) => {
const box = result.box;
@@ -87,23 +99,24 @@ export class UploadImageModalComponent implements AfterViewInit, OnDestroy {
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})
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.resetFileInput();
// Schließe das Upload-Modal
// Close the upload modal
this.closeModal();
} catch (error) {
console.error('Fehler beim OCR-Service:', error);
this.processingStatus = 'Fehler beim OCR-Service';
console.error('Error with OCR service:', error);
this.processingStatus = 'Error with OCR service';
this.loading = false;
}
};
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 {
if (this.imageFileElement && this.imageFileElement.nativeElement) {