Compare commits

...

3 Commits

Author SHA1 Message Date
ebbaf6716d feat: implement message bar and enhance chat functionality
- Added MessageBarComponent for sending messages.
- Integrated message sending logic in ChatService.
- Updated FeedComponent to scroll to the bottom on new messages.
- Improved layout and styling for chat components.
- Adjusted environment configuration for API base URL.
2025-06-07 02:42:59 +02:00
757e593373 messages 2025-06-06 16:17:10 +02:00
543dc2b9fb list channels 2025-06-05 14:34:53 +02:00
24 changed files with 303 additions and 209 deletions

View File

@ -74,7 +74,8 @@
"buildTarget": "ui:build:production" "buildTarget": "ui:build:production"
}, },
"development": { "development": {
"buildTarget": "ui:build:development" "buildTarget": "ui:build:development",
"proxyConfig": "proxy.conf.json"
} }
}, },
"defaultConfiguration": "development" "defaultConfiguration": "development"

8
proxy.conf.json Normal file
View File

@ -0,0 +1,8 @@
{
"/api": {
"target": "http://localhost:5000",
"secure": false,
"ws": true,
"changeOrigin": true
}
}

View File

@ -13,8 +13,7 @@
button { button {
display: block; display: block;
margin-bottom: 10px 0;
} }
} }
} }

View File

@ -11,7 +11,7 @@ import { Router } from '@angular/router';
styleUrls: ['../auth.module.scss', './login.component.scss'] styleUrls: ['../auth.module.scss', './login.component.scss']
}) })
export class LoginComponent implements OnInit { export class LoginComponent implements OnInit {
loginForm!: FormGroup; public loginForm!: FormGroup;
constructor( constructor(
private authService: AuthService, private authService: AuthService,
@ -41,7 +41,7 @@ export class LoginComponent implements OnInit {
this.router.navigateByUrl('chat'); this.router.navigateByUrl('chat');
} }
}, },
error: _ => { error: () => {
this.toastrService.error("API error", "Error"); this.toastrService.error("API error", "Error");
} }
}) })

View File

@ -12,6 +12,11 @@ import { ToolbarComponent } from '../common/toolbar/toolbar.component';
import { MatBadgeModule } from '@angular/material/badge'; import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { MatIconModule } from '@angular/material/icon';
import { MessageBarComponent } from './chat/message-bar/message-bar.component';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({ @NgModule({
declarations: [ declarations: [
@ -20,7 +25,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
FeedComponent, FeedComponent,
ChannelEntryComponent, ChannelEntryComponent,
MessageComponent, MessageComponent,
ProfilePictureComponent ProfilePictureComponent,
MessageBarComponent
], ],
imports: [ imports: [
CommonModule, CommonModule,
@ -28,7 +34,11 @@ import { MatTooltipModule } from '@angular/material/tooltip';
ToolbarComponent, ToolbarComponent,
MatBadgeModule, MatBadgeModule,
MatButtonModule, MatButtonModule,
MatTooltipModule MatTooltipModule,
MatIconModule,
MatFormFieldModule,
MatInputModule,
ReactiveFormsModule
] ]
}) })
export class ChatModule { } export class ChatModule { }

View File

@ -1,5 +1,5 @@
button { button {
width: 70%; width: 95%;
display: block; display: block;
margin: 10px auto; margin: 5px auto;
} }

View File

@ -1,4 +1,4 @@
import { Component, EventEmitter, OnChanges, OnDestroy, OnInit, Output } from '@angular/core'; import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { Channel } from '../../../models/channel'; import { Channel } from '../../../models/channel';
import { ChatService } from '../../../services/chat.service'; import { ChatService } from '../../../services/chat.service';
import { Subject, takeUntil } from 'rxjs'; import { Subject, takeUntil } from 'rxjs';
@ -20,7 +20,7 @@ export class ChannelListComponent implements OnInit, OnDestroy {
constructor(private chatService: ChatService) { } constructor(private chatService: ChatService) { }
ngOnInit() { ngOnInit() {
this.chatService.ListChannels() this.chatService.ListAvailableChannels()
.pipe(takeUntil(this.destroy)) .pipe(takeUntil(this.destroy))
.subscribe(channels => { .subscribe(channels => {
this.channels = channels; this.channels = channels;

View File

@ -1,6 +1,9 @@
<app-toolbar />
<div id="container"> <div id="container">
<app-toolbar />
<app-channel-list (select)="Select($event)"></app-channel-list> <app-channel-list (select)="Select($event)"></app-channel-list>
<app-feed [channel]="this.selectedChannel"></app-feed> <app-feed [channel]="this.selectedChannel"></app-feed>
<app-message-bar [channel]="this.selectedChannel?.id ?? 1"></app-message-bar>
</div> </div>

View File

@ -1,5 +1,35 @@
#container { #container {
display: grid;
grid-template-columns: minmax(auto, 150px) 1fr;
height: 100%; height: 100%;
display: grid;
grid-template-columns: 150px 1fr;
grid-template-rows: 65px 1fr auto;
gap: 0px;
app-toolbar {
grid-column: span 2 / span 2;
}
app-channel-list {
grid-row: span 2 / span 2;
grid-row-start: 2;
}
app-feed {
grid-row-start: 2;
border-left: 2px solid var(--mat-sys-surface-variant);
border-top: 2px solid var(--mat-sys-surface-variant);
border-radius: 10px 0 0 0;
background-color: var(--mat-sys-background);
}
app-message-bar {
grid-column-start: 2;
grid-row-start: 3;
border-left: 2px solid var(--mat-sys-surface-variant);
}
} }

View File

@ -1,4 +1,3 @@
<app-message <div #scrollable id="scrollable">
*ngFor="let message of this.messages" <app-message *ngFor="let message of this.messages" [message]="message" />
[message]="message" </div>
/>

View File

@ -1,7 +1,3 @@
:host { :host {
border-left: 2px solid var(--mat-sys-surface-variant); overflow-y: scroll;
border-top: 2px solid var(--mat-sys-surface-variant);
border-radius: 10px 0;
background-color: var(--mat-sys-background);
} }

View File

@ -1,7 +1,6 @@
import { Component, Input, OnChanges, OnDestroy, OnInit } from '@angular/core'; import { AfterContentInit, AfterViewChecked, AfterViewInit, Component, ElementRef, Input, OnChanges, OnDestroy, ViewChild } from '@angular/core';
import { Message } from '../../../models/message'; import { Message } from '../../../models/message';
import { ChatService } from '../../../services/chat.service'; import { ChatService } from '../../../services/chat.service';
import { UserService } from '../../../services/user.service';
import { Channel } from '../../../models/channel'; import { Channel } from '../../../models/channel';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
@ -11,7 +10,7 @@ import { Subscription } from 'rxjs';
templateUrl: './feed.component.html', templateUrl: './feed.component.html',
styleUrl: './feed.component.scss' styleUrl: './feed.component.scss'
}) })
export class FeedComponent implements OnChanges, OnDestroy { export class FeedComponent implements OnChanges, OnDestroy, AfterViewInit {
private readonly DEFAULT_CHANNEL_ID: number = 1; private readonly DEFAULT_CHANNEL_ID: number = 1;
@Input('channel') public channel?: Channel; @Input('channel') public channel?: Channel;
@ -19,9 +18,13 @@ export class FeedComponent implements OnChanges, OnDestroy {
public subscription?: Subscription; public subscription?: Subscription;
constructor(private chatService: ChatService) { } constructor(private chatService: ChatService, private element: ElementRef<HTMLElement>) { }
ngOnChanges() { ngAfterViewInit(): void {
this.scrollToBottom();
}
ngOnChanges(): void {
if (this.subscription) { if (this.subscription) {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
this.messages = []; this.messages = [];
@ -29,7 +32,11 @@ export class FeedComponent implements OnChanges, OnDestroy {
this.subscription = this.subscription =
this.chatService.GetMessages(this.channel?.id ?? this.DEFAULT_CHANNEL_ID) this.chatService.GetMessages(this.channel?.id ?? this.DEFAULT_CHANNEL_ID)
.subscribe(message => this.messages.push(message)); .subscribe(message => {
this.messages.push(message);
if (this.isAtBottom()) this.scrollToBottom();
});
} }
ngOnDestroy(): void { ngOnDestroy(): void {
@ -37,4 +44,13 @@ export class FeedComponent implements OnChanges, OnDestroy {
this.subscription.unsubscribe(); this.subscription.unsubscribe();
} }
} }
private isAtBottom(): boolean {
let element = this.element.nativeElement;
return Math.abs(element.scrollHeight - element.clientHeight - element.scrollTop) <= 100;
}
private scrollToBottom(): void {
setTimeout(() => this.element.nativeElement.scrollTop = this.element.nativeElement.scrollHeight, 100);
}
} }

View File

@ -1,8 +1,8 @@
<div class="message-container"> <div class="message-container">
<app-profile-picture [username]="this.message.sender" /> <app-profile-picture [username]="this.message.sender_name" />
<div class="message-inner-container"> <div class="message-inner-container">
<div class="message-sender">{{this.message.sender}}</div> <div class="message-sender">{{this.message.sender_name}}</div>
<div class="message-content">{{this.message.content}}</div> <div class="message-content">{{this.message.content}}</div>
</div> </div>

View File

@ -1 +1,2 @@
<img [src]="this.url" [alt]="this.username"> <img *ngIf="this.url != ''" [src]="this.url" [alt]="this.username">
<mat-icon *ngIf="this.url == ''">face</mat-icon>

View File

@ -1,7 +1,23 @@
img { :host {
display: inline-block; display: inline-block;
width: 100%; width: 100%;
aspect-ratio: 1;
border-radius: 50%; border-radius: 50%;
box-shadow: 0px 0px 5px var(--mat-sys-on-background); box-shadow: 0px 0px 2px var(--mat-sys-on-background);
}
// style alt for missing images
img {
display: flex;
justify-content: center;
padding-top: 15px;
overflow: hidden;
}
mat-icon {
width: 100% !important;
height: 100% !important;
text-align: center;
font-size: 50px;
} }

View File

@ -0,0 +1,12 @@
<form [formGroup]="messageForm" (submit)="Send()">
<mat-form-field>
<mat-label>Message</mat-label>
<textarea type="textarea" required matInput formControlName="content"></textarea>
</mat-form-field>
<button mat-button type="button" (click)="Send()">
<mat-icon>send</mat-icon>
</button>
</form>

View File

@ -0,0 +1,23 @@
form {
align-items: center;
padding: 10px;
display: grid;
grid-template-columns: 1fr auto;
mat-form-field {
padding-top: 5px;
}
}
button {
margin: 0 5px;
transform: translateY(-10px);
mat-icon {
margin: auto;
vertical-align: middle;
}
}

View File

@ -0,0 +1,44 @@
import { Component, Input, OnInit } from '@angular/core';
import { ChatService } from '../../../services/chat.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-message-bar',
standalone: false,
templateUrl: './message-bar.component.html',
styleUrl: './message-bar.component.scss'
})
export class MessageBarComponent implements OnInit {
private readonly MAX_MESSAGE_LENGTH: number = 120;
@Input('channel') channel!: number;
public messageForm!: FormGroup;
constructor(private chatService: ChatService,
private formBuilder: FormBuilder,
private toastrService: ToastrService) { }
ngOnInit(): void {
this.messageForm = this.formBuilder.group({
content: new FormControl('', [
Validators.required,
Validators.minLength(1),
Validators.maxLength(this.MAX_MESSAGE_LENGTH)
])
});
}
public Send(): void {
if (this.messageForm.valid) {
this.chatService.SendMessage(
this.channel,
this.messageForm.get("content")!.value).subscribe(
{
next: () => this.messageForm.setValue({ "content": "" }),
error: () => this.toastrService.error("Failed to send message.", "Error")
});
}
}
}

View File

@ -1,9 +1,7 @@
import { Timestamp } from "rxjs"
export class Message { export class Message {
public id!: number public id!: number
public sender!: string public sender_name!: string
public channel!: number public channel_id!: number
public time!: Date public time!: Date
public content!: string public content!: string
} }

View File

@ -1,6 +1,6 @@
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of } from 'rxjs'; import { catchError, map, Observable, of, tap } from 'rxjs';
import { LoginResponse, RegisterResponse } from './responses/auth'; import { LoginResponse, RegisterResponse } from './responses/auth';
import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot } from '@angular/router'; import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot } from '@angular/router';
import { environment } from '../../environment/environment'; import { environment } from '../../environment/environment';
@ -14,6 +14,8 @@ export class AuthService {
private readonly PASSWORD_FIELD: string = "password"; private readonly PASSWORD_FIELD: string = "password";
private readonly REPEAT_PASSWORD_FIELD: string = "repeatPassword"; private readonly REPEAT_PASSWORD_FIELD: string = "repeatPassword";
private loggedIn: boolean = false;
constructor(private http: HttpClient) { } constructor(private http: HttpClient) { }
public Login(username: string, password: string): Observable<LoginResponse> { public Login(username: string, password: string): Observable<LoginResponse> {
@ -51,29 +53,40 @@ export class AuthService {
return this.http.get(url, { withCredentials: true }).pipe( return this.http.get(url, { withCredentials: true }).pipe(
map(() => true), map(() => true),
catchError(() => of(false)) catchError(() => of(false)),
tap(result => this.loggedIn = result)
); );
} }
public IsLoggedIn(): boolean { public HasToken(): boolean {
let cookies = document.cookie.split(';'); let cookies = document.cookie.split(';');
let found = false; let found = false;
cookies.forEach(cookie => { cookies.forEach(cookie => {
cookie = cookie.trim(); cookie = cookie.trim();
found = found || cookie.startsWith(this.SESSION_COOKIE + "=") && cookie.split('=', 2)[1] != ''; found = found || cookie.startsWith(this.SESSION_COOKIE + "=") && cookie.split('=', 2)[1] != '';
}); });
return found; return found;
} }
public IsLoggedIn(): boolean { return this.loggedIn; }
} }
export const IsLoggedInCanActivate: CanActivateFn = ( export const IsLoggedInCanActivate: CanActivateFn = (
_: ActivatedRouteSnapshot, _: ActivatedRouteSnapshot,
__: RouterStateSnapshot __: RouterStateSnapshot
) => { ): Observable<boolean> => {
if (inject(AuthService).IsLoggedIn()) { const authService = inject(AuthService);
return true; const router = inject(Router);
} else {
inject(Router).navigateByUrl("auth/login"); return authService.Bump().pipe(
return false; map(isValid => {
} if (isValid) {
} return true;
} else {
router.navigate(['auth/login']);
return false;
}
})
);
};

View File

@ -1,173 +1,85 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { from, Observable } from 'rxjs'; import { catchError, from, map, merge, mergeMap, Observable, throwError } from 'rxjs';
import { webSocket } from 'rxjs/webSocket';
import { Channel } from '../models/channel'; import { Channel } from '../models/channel';
import { Message } from '../models/message'; import { Message } from '../models/message';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environment/environment';
import { GetMessagesResponse, ListAvailableChannelsResponse, SendMessageResponse } from './responses/chat';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class ChatService { export class ChatService {
constructor() { } private readonly CHANNEL: string = "channel_id";
private readonly CONTENT: string = "content";
// TODO: implement constructor(private http: HttpClient) { }
public ListChannels(): Observable<Channel[]> {
return new Observable<Channel[]>(subscriber => { public ListAvailableChannels(): Observable<Channel[]> {
subscriber.next([ let url = `${environment.apiBase}/chat/channels`
{ return this.http.get<ListAvailableChannelsResponse>(url, { withCredentials: true })
id: 0, .pipe(
name: 'default', map(response => {
description: 'this is the default channel' if (response.error) {
}, throw new Error(response.error);
{ }
id: 1,
name: 'XIV. Leo', if (response.channels) {
description: 'this is another channel' return response.channels;
}, }
]);
subscriber.complete(); throw new Error("bad API response, missing channels with no error");
}); }),
catchError(error => throwError(() => new Error(error.error.message)))
);
} }
// TODO: implement
// TODO: refactor this so it first returns the n last messages,
// then listens for incoming messages and forwards them as they come
public GetMessages(channelID: number): Observable<Message> { public GetMessages(channelID: number): Observable<Message> {
let url = `${environment.apiBase}/chat/messages/${channelID}`;
let messages: Observable<Message[]> =
this.http.get<GetMessagesResponse>(url, { withCredentials: true })
.pipe(
map(response => {
if (response.error) {
throw new Error(response.error);
}
return from([ if (response.messages) {
{ return response.messages;
id: 1, }
sender: 'admin',
channel: 1, throw new Error("bad API response, missing messages with no error");
time: new Date(), }),
content: 'this is my first message' catchError(error => throwError(() => new Error(error.error.message)))
}, );
{
id: 1, url = `${environment.apiBase}/chat/subscribe/${channelID}`;
sender: 'admin', let socket = webSocket<Message>(url);
channel: 1,
time: new Date(), return merge(
content: 'this is my first message' messages.pipe(mergeMap(msgArray => from(msgArray))),
}, socket.asObservable());
{ }
id: 1,
sender: 'admin', public SendMessage(channel: number, content: string): Observable<SendMessageResponse> {
channel: 1, let url = `${environment.apiBase}/chat/send`;
time: new Date(),
content: 'this is my first message' let data = new FormData();
}, data.append(this.CHANNEL, channel.toString());
{ data.append(this.CONTENT, content);
id: 1,
sender: 'admin', return this.http.post<SendMessageResponse>(url, data, { withCredentials: true })
channel: 1, .pipe(
time: new Date(), map(response => {
content: 'this is my first message' if (response.error) {
}, throw new Error(response.error);
{ }
id: 1,
sender: 'admin', return response;
channel: 1, }),
time: new Date(), catchError(error => throwError(() => new Error(error.error.message)))
content: 'this is my first message' );
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 1,
sender: 'admin',
channel: 1,
time: new Date(),
content: 'this is my first message'
},
{
id: 2,
sender: 'admin',
channel: 2,
time: new Date(),
content: 'this is my second message'
}
]);
} }
} }

View File

@ -0,0 +1,13 @@
import { Channel } from "../../models/channel";
import { Message } from "../../models/message";
import { APIResponse } from "./basic";
export class ListAvailableChannelsResponse extends APIResponse {
public channels?: Channel[];
}
export class GetMessagesResponse extends APIResponse {
public messages?: Message[];
}
export class SendMessageResponse extends APIResponse { }

View File

@ -1,4 +1,4 @@
export const environment = { export const environment = {
production: false, production: false,
apiBase: "http://localhost:5000" apiBase: "/api"
} }

View File

@ -2,7 +2,7 @@
html, html,
body { body {
height: 100%; height: 100dvh;
margin: 0; margin: 0;
font-family: var(--mat-sys-body-medium-font); font-family: var(--mat-sys-body-medium-font);