Ajout d'un composant de chargement et update du formulaire

This commit is contained in:
guams 2025-05-07 19:50:04 +02:00
parent f9b8f4f2a8
commit 2e357e1b59
21 changed files with 243 additions and 72 deletions

View File

@ -0,0 +1,24 @@
div {
margin-top: 10em;
display: flex;
justify-content: center;
align-items: center;
}
img {
animation-name: spin;
animation-duration: 2000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
max-width: 40%;
max-height: 40%;
}
@keyframes spin {
from {
transform:rotate(0deg);
}
to {
transform:rotate(360deg);
}
}

View File

@ -0,0 +1,3 @@
<div>
<img src="./assets/icon.jpg" alt="loadign">
</div>

View File

@ -0,0 +1,15 @@
import { Component } from '@angular/core';
import {NgOptimizedImage} from '@angular/common';
@Component({
selector: 'app-loading',
standalone: true,
imports: [
NgOptimizedImage
],
templateUrl: './loading.component.html',
styleUrl: './loading.component.css'
})
export class LoadingComponent {
}

View File

@ -0,0 +1,15 @@
@if (post) {
<p-dialog class="preview-dialog"
header='Prévisualisation de "{{ post.title }}"'
[modal]="true"
[(visible)]="opened"
[closable]="true">
<app-post-home [title]="post.title"
[description]="post.description"
[category]="post.category"
[date]="post.publicationDate"
[illustration]="post.illustration"
[authorProfilePicture]="profilePicture"
[username]="username"/>
</p-dialog>
}

View File

@ -0,0 +1,21 @@
import {Component, Input} from '@angular/core';
import {Dialog} from 'primeng/dialog';
import {PostHomeComponent} from '../../post-home/post-home.component';
import {Post} from '../../../models/post';
@Component({
selector: 'app-preview-modal',
standalone: true,
imports: [
Dialog,
PostHomeComponent
],
templateUrl: './preview-modal.component.html',
styleUrl: './preview-modal.component.css'
})
export class PreviewModalComponent {
opened: boolean = true;
@Input({required: true}) post: Post | undefined;
@Input() username: string = '';
@Input() profilePicture: string = '';
}

View File

@ -0,0 +1,15 @@
@if (post) {
<p-dialog header='Modifier "{{ post.title }}"'
[modal]="true"
[closable]="true"
[(visible)]="opened">
<app-post-form [actualAuthor]="actualAuthor"
[postId]="post.id"
[isUpdateMode]="true"
[title]="post.title"
[category]="post.category"
[description]="post.description"
[body]="post.body"
(postUpdate)="onSubmit(post)"/>
</p-dialog>
}

View File

@ -0,0 +1,33 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {Dialog} from 'primeng/dialog';
import {PostFormComponent} from '../../post-form/post-form.component';
import {Post} from '../../../models/post';
import {AuthService} from '../../../auth.service';
import {Author} from '../../../models/author';
@Component({
selector: 'app-update-modal',
standalone: true,
imports: [
Dialog,
PostFormComponent
],
templateUrl: './update-modal.component.html',
styleUrl: './update-modal.component.css'
})
export class UpdateModalComponent {
actualAuthor: Author | undefined;
opened: boolean = true;
@Input({required: true}) post: Post | undefined;
@Output() updatedPost: EventEmitter<Post> = new EventEmitter<Post>();
constructor(private authService: AuthService) {
this.authService.getAuthenticatedAuthor();
}
onSubmit(updatedPost: Post) {
this.updatedPost.emit(updatedPost);
this.opened = false
}
}

View File

@ -1,13 +1,20 @@
<div> <div>
<form [formGroup]="form" (ngSubmit)="onSubmit()"> <form [formGroup]="form" (ngSubmit)="onSubmit()">
<label for="title">Titre du post</label> <p-floatlabel variant="on">
<input [(ngModel)]="title" id="title" type="text" pInputText formControlName="title" /> <input [(ngModel)]="title" id="title" type="text" pInputText formControlName="title"/>
<label for="title">Titre du post</label>
</p-floatlabel>
<label for="category">Catégorie du post</label> <p-floatlabel variant="on">
<input [(ngModel)]="category" pInputText id="category" formControlName="category" type="text" /> <input [(ngModel)]="category" pInputText id="category" formControlName="category" type="text"/>
<label for="category">Catégorie du post</label>
</p-floatlabel>
<p-floatlabel variant="on">
<textarea pTextarea id="desc" rows="5" cols="30" pSize="large" formControlName="description"></textarea>
<label for="desc">Description du post</label>
</p-floatlabel>
<label for="desc">Description du post</label>
<textarea [(ngModel)]="description" formControlName="description" id="desc" pInputTextarea></textarea>
<label>Image descriptive du post</label> <label>Image descriptive du post</label>
<p-fileUpload <p-fileUpload
@ -28,7 +35,43 @@
</p-fileUpload> </p-fileUpload>
<label>Contenu du post</label> <label>Contenu du post</label>
<p-editor [(ngModel)]="body" formControlName="body" [modules]="editorModules" [style]="{ height: '320px' }"> <p-editor [(ngModel)]="body" formControlName="body" [style]="{ height: '320px' }">
<ng-template #header>
<span class="ql-formats">
<!-- <button type="button" class="ql-list" value="ordered"></button>-->
<!-- <button type="button" class="ql-bullet" value="bullet"></button>-->
<select class="ql-header">
<option value="1">Titre 1</option>
<option value="2">Titre 2</option>
<option value="3">Titre 3</option>
<option value="4">Titre 4</option>
<option value="5">Titre 5</option>
<option value="6">Titre 6</option>
<option value="">Normal</option>
</select>
<button class="ql-bold"></button>
<button class="ql-italic"></button>
<button class="ql-underline"></button>
<button class="ql-strike"></button>
<span class="ql-formats">
<select class="ql-color"></select>
<select class="ql-background"></select>
</span>
<span class="ql-formats">
<button class="ql-script" value="sub"></button>
<button class="ql-script" value="super"></button>
</span>
<span class="ql-formats">
<button class="ql-blockquote"></button>
<button class="ql-code-block"></button>
</span>
<button type="button" class="ql-list" value="bullet"></button>
<button type="button" class="ql-list" value="ordered"></button>
<button type="button" class="ql-link" aria-label="Link"></button>
<button type="button" class="ql-image" aria-label="Image"></button>
<button type="button" class="ql-video" aria-label="Video"></button>
</span>
</ng-template>
</p-editor> </p-editor>
<p-button <p-button

View File

@ -1,4 +1,4 @@
import {Component, Input, OnDestroy} from '@angular/core'; import {Component, EventEmitter, Input, OnDestroy, Output} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms'; import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext'; import {InputTextModule} from 'primeng/inputtext';
import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload'; import {FileSelectEvent, FileUploadModule} from 'primeng/fileupload';
@ -11,6 +11,9 @@ import {Author} from '../../models/author';
import {AuthorService} from '../../services/author.service'; import {AuthorService} from '../../services/author.service';
import {AuthService} from '../../auth.service'; import {AuthService} from '../../auth.service';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {Textarea} from 'primeng/textarea';
import {FloatLabel} from 'primeng/floatlabel';
import {Post} from '../../models/post';
@Component({ @Component({
selector: 'app-post-form', selector: 'app-post-form',
@ -20,7 +23,9 @@ import {Button} from 'primeng/button';
InputTextModule, InputTextModule,
FileUploadModule, FileUploadModule,
EditorModule, EditorModule,
Button Button,
Textarea,
FloatLabel
], ],
templateUrl: './post-form.component.html', templateUrl: './post-form.component.html',
styleUrls: ['./post-form.component.css'] styleUrls: ['./post-form.component.css']
@ -33,17 +38,10 @@ export class PostFormComponent implements OnDestroy {
@Input() category: string = ''; @Input() category: string = '';
@Input() description: string = ''; @Input() description: string = '';
@Input() body: string = ''; @Input() body: string = '';
@Output() postUpdate: EventEmitter<Post> = new EventEmitter();
subs: Subscription[] = []; subs: Subscription[] = [];
form: FormGroup; form: FormGroup;
uploadedFile: File | undefined; uploadedFile: File | undefined;
editorModules = {
toolbar: [
['bold', 'italic', 'underline', 'code'], // Styles de texte
[{header: [2, false]}], // Permet d'ajouter un `<h2>`
[{list: 'ordered'}, {list: 'bullet'}], // Listes
['link', 'image', 'video'], // Ajout de liens et images
],
};
constructor( constructor(
private formBuilder: FormBuilder, private formBuilder: FormBuilder,
@ -111,6 +109,7 @@ export class PostFormComponent implements OnDestroy {
}) })
).subscribe({ ).subscribe({
next: (_) => { next: (_) => {
this.postUpdate.emit(_);
this.successMessage('Succès', 'Post mis à jour avec succès') this.successMessage('Succès', 'Post mis à jour avec succès')
}, },
error: (err) => this.failureMessage('Erreur', err.error.message) error: (err) => this.failureMessage('Erreur', err.error.message)
@ -140,6 +139,7 @@ export class PostFormComponent implements OnDestroy {
} }
private transformYouTubeLinksToIframes(html: string): string { private transformYouTubeLinksToIframes(html: string): string {
// Magie noire
return html.replace(/<a[^>]*href="(https?:\/\/(?:www\.)?(youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)[^"]*)".*?<\/a>/g, return html.replace(/<a[^>]*href="(https?:\/\/(?:www\.)?(youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)[^"]*)".*?<\/a>/g,
(_, _url, _prefix, videoId) => { (_, _url, _prefix, videoId) => {
return `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`; return `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`;

View File

@ -13,6 +13,6 @@
[authorProfilePicture]="post.authorProfilePicture"/> [authorProfilePicture]="post.authorProfilePicture"/>
} }
} @else { } @else {
<h1>Aucun post n'a été créé pour l'instant</h1> <app-loading></app-loading>
} }
</div> </div>

View File

@ -8,6 +8,7 @@ import {PostService} from '../../services/post.service';
import {PostHomeComponent} from '../../components/post-home/post-home.component'; import {PostHomeComponent} from '../../components/post-home/post-home.component';
import {AuthorWithPost} from '../../models/author-with-post'; import {AuthorWithPost} from '../../models/author-with-post';
import {AuthService} from '../../auth.service'; import {AuthService} from '../../auth.service';
import {LoadingComponent} from '../../components/loading/loading.component';
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
@ -17,6 +18,7 @@ import {AuthService} from '../../auth.service';
HeaderComponent, HeaderComponent,
ToastModule, ToastModule,
PostHomeComponent, PostHomeComponent,
LoadingComponent,
], ],
templateUrl: './home.component.html', templateUrl: './home.component.html',
styleUrl: './home.component.css' styleUrl: './home.component.css'

View File

@ -5,10 +5,7 @@
<label for="username">Nom d'utilisateur</label> <label for="username">Nom d'utilisateur</label>
<input type="text" id="username" pInputText [(ngModel)]="name"/> <input type="text" id="username" pInputText [(ngModel)]="name"/>
<label for="password">Mot de passe</label> <label for="password">Mot de passe</label>
<input type="password" id="password" pInputText [(ngModel)]="password"/> <input type="password" id="password" pInputText [(ngModel)]="password" (keyup.enter)="sendLogins()"/>
<label for="confirm-password">Confirmez le mot de passe</label>
<input type="password" id="confirm-password" pInputText
[(ngModel)]="confirmPassword" (keyup.enter)="sendLogins()"/>
<p-button <p-button
class="send-button" class="send-button"
label="Se connecter" label="Se connecter"

View File

@ -29,7 +29,6 @@ export class LoginComponent implements OnDestroy {
name: string = ""; name: string = "";
actualAuthor: Author | undefined; actualAuthor: Author | undefined;
password: string = ""; password: string = "";
confirmPassword: string = "";
subs: Subscription[] = []; subs: Subscription[] = [];
constructor(private authorService: AuthorService, constructor(private authorService: AuthorService,
@ -39,31 +38,27 @@ export class LoginComponent implements OnDestroy {
} }
sendLogins(): void { sendLogins(): void {
if (this.password === this.confirmPassword) { this.subs.push
this.subs.push (
( this.authorService.login(this.name, this.password).pipe(
this.authorService.login(this.name, this.password).pipe( switchMap((tokenObj: any) => {
switchMap((tokenObj: any) => { // sessionStorage.removeItem('token');
// sessionStorage.removeItem('token'); sessionStorage.setItem('token', tokenObj.token);
sessionStorage.setItem('token', tokenObj.token); return this.authorService.me(tokenObj.token)
return this.authorService.me(tokenObj.token) }))
})) .subscribe({
.subscribe({ next: (author: Author) => {
next: (author: Author) => { // sessionStorage.removeItem('author');
// sessionStorage.removeItem('author'); sessionStorage.setItem('author', JSON.stringify(author));
sessionStorage.setItem('author', JSON.stringify(author)); sessionStorage.setItem('token-expiration-date', DateTime.now().plus({millisecond: this.configurationService.getTokenTTL()}).toISO())
sessionStorage.setItem('token-expiration-date', DateTime.now().plus({millisecond: this.configurationService.getTokenTTL()}).toISO()) this.getAuthorCookie();
this.getAuthorCookie(); this.router.navigate(['/']).then(() => {
this.router.navigate(['/']).then(() => { this.successMessage('Connecté avec succès', 'Heureux de vous revoir ' + this.actualAuthor?.name)
this.successMessage('Connecté avec succès', 'Heureux de vous revoir ' + this.actualAuthor?.name) });
}); },
}, error: (err) => this.failureMessage('Erreur de connexion', err.error.message)
error: (err) => this.failureMessage('Erreur de connexion', err.error.message) })
}) );
);
} else {
this.failureMessage('Erreur de connexion', 'Les deux mots de passe ne correspondent pas')
}
} }
getAuthorCookie(): void { getAuthorCookie(): void {

View File

@ -23,29 +23,10 @@
<td>{{ post.publicationDate | date: "dd/MM/yyyy à HH:mm" }}</td> <td>{{ post.publicationDate | date: "dd/MM/yyyy à HH:mm" }}</td>
<td>{{ post.description }}</td> <td>{{ post.description }}</td>
<td> <td>
<p-button icon="pi pi-eye" (click)="openDialog(previewDialogVisibility, rowIndex)" severity="info" <p-button icon="pi pi-eye" (click)="openDialogPreview(post)" severity="info" label="Prévisualiser"/>
label="Prévisualiser"/>
<p-dialog class="preview-dialog" header='Prévisualisation de "{{ post.title }}"' [modal]="true"
[(visible)]="previewDialogVisibility[rowIndex]">
<app-post-home [title]="post.title"
[description]="post.description"
[category]="post.category"
[date]="post.publicationDate"
[illustration]="post.illustration"/>
</p-dialog>
</td> </td>
<td> <td>
<p-button icon="pi pi-pencil" (click)="openDialog(updateDialogVisibility, rowIndex)" severity="warn" <p-button icon="pi pi-pencil" (click)="openDialogUpdate(post)" severity="warn" label="Modifier"/>
label="Modifier"/>
<p-dialog header='Modifier "{{ post.title }}"' [modal]="true" [(visible)]="updateDialogVisibility[rowIndex]">
<app-post-form [actualAuthor]="actualAuthor"
[postId]="post.id"
[isUpdateMode]="true"
[title]="post.title"
[category]="post.category"
[description]="post.description"
[body]="post.body"/>
</p-dialog>
</td> </td>
<td> <td>
<p-button icon="pi pi-trash" (click)="openDialog(deleteDialogVisibility, rowIndex)" severity="danger" <p-button icon="pi pi-trash" (click)="openDialog(deleteDialogVisibility, rowIndex)" severity="danger"

View File

@ -1,4 +1,4 @@
import {Component, OnDestroy} from '@angular/core'; import {Component, OnDestroy, ViewContainerRef} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component'; import {HeaderComponent} from '../../components/header/header.component';
import {TableModule} from 'primeng/table'; import {TableModule} from 'primeng/table';
import {AuthorService} from '../../services/author.service'; import {AuthorService} from '../../services/author.service';
@ -14,6 +14,8 @@ import {PostHomeComponent} from '../../components/post-home/post-home.component'
import {PostService} from '../../services/post.service'; import {PostService} from '../../services/post.service';
import {PostFormComponent} from "../../components/post-form/post-form.component"; import {PostFormComponent} from "../../components/post-form/post-form.component";
import {AuthService} from '../../auth.service'; import {AuthService} from '../../auth.service';
import {PreviewModalComponent} from '../../components/modal/preview-modal/preview-modal.component';
import {UpdateModalComponent} from '../../components/modal/update-modal/update-modal.component';
@Component({ @Component({
selector: 'app-my-posts', selector: 'app-my-posts',
@ -33,7 +35,6 @@ import {AuthService} from '../../auth.service';
}) })
export class MyPostsComponent implements OnDestroy { export class MyPostsComponent implements OnDestroy {
subs: Subscription[] = []; subs: Subscription[] = [];
previewDialogVisibility: boolean[] = [];
updateDialogVisibility: boolean[] = []; updateDialogVisibility: boolean[] = [];
deleteDialogVisibility: boolean[] = []; deleteDialogVisibility: boolean[] = [];
posts: Post[] = []; posts: Post[] = [];
@ -42,11 +43,13 @@ export class MyPostsComponent implements OnDestroy {
constructor(private authService: AuthService, constructor(private authService: AuthService,
private postService: PostService, private postService: PostService,
private viewContainer: ViewContainerRef,
private authorService: AuthorService, private authorService: AuthorService,
private messageService: MessageService) { private messageService: MessageService) {
const authenticatedAuthor = this.authService.getAuthenticatedAuthor(); const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
if (authenticatedAuthor) { if (authenticatedAuthor) {
this.actualAuthor = authenticatedAuthor; this.actualAuthor = authenticatedAuthor;
this.authorService.getAuthorAvatar(this.actualAuthor.id).subscribe(avatar => this.actualAuthor!.profilePicture = avatar);
} }
this.updatePosts(); this.updatePosts();
} }
@ -98,6 +101,24 @@ export class MyPostsComponent implements OnDestroy {
}); });
} }
openDialogPreview(post: Post): void {
const modalInstance = this.viewContainer.createComponent(PreviewModalComponent);
modalInstance.setInput("post", post)
modalInstance.setInput("username", this.actualAuthor?.name)
modalInstance.setInput("profilePicture", this.actualAuthor?.profilePicture)
}
openDialogUpdate(post: Post): void {
const modalInstance = this.viewContainer.createComponent(UpdateModalComponent);
modalInstance.setInput("post", post)
modalInstance.instance.updatedPost.subscribe(post => {
console.log(this.posts.map(a => a.id).indexOf(post.id))
this.posts[this.posts.map(a => a.id).indexOf(post.id)] = post
this.posts = [... this.posts]
modalInstance.destroy();
});
}
openDialog(dialogBooleanTab: boolean[], index: number) { openDialog(dialogBooleanTab: boolean[], index: number) {
dialogBooleanTab[index] = true; dialogBooleanTab[index] = true;
} }

View File

@ -30,5 +30,5 @@
</div> </div>
</div> </div>
} @else { } @else {
<h1>Loading...</h1> <app-loading></app-loading>
} }

View File

@ -10,6 +10,7 @@ import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog'; import {DialogModule} from 'primeng/dialog';
import {UpdateProfileFormComponent} from '../../components/update-profile-form/update-profile-form.component'; import {UpdateProfileFormComponent} from '../../components/update-profile-form/update-profile-form.component';
import {AuthService} from '../../auth.service'; import {AuthService} from '../../auth.service';
import {LoadingComponent} from '../../components/loading/loading.component';
@Component({ @Component({
selector: 'app-profile', selector: 'app-profile',
@ -21,6 +22,7 @@ import {AuthService} from '../../auth.service';
Button, Button,
DialogModule, DialogModule,
UpdateProfileFormComponent, UpdateProfileFormComponent,
LoadingComponent,
], ],
templateUrl: './profile.component.html', templateUrl: './profile.component.html',
styleUrl: './profile.component.css' styleUrl: './profile.component.css'

View File

@ -91,4 +91,8 @@ export class AuthorService {
} }
return this.httpClient.post<Author>(`${this.apiUrl}/register/admin`, {name: username, password: password, role: role}, httpOptions); return this.httpClient.post<Author>(`${this.apiUrl}/register/admin`, {name: username, password: password, role: role}, httpOptions);
} }
getAuthorAvatar(id: string) {
return this.httpClient.get<string>(`${this.apiUrl}/${id}/avatar`);
}
} }

BIN
src/assets/icon.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB