First commit

This commit is contained in:
2025-08-16 22:03:31 +03:00
Unverified
commit b561e85419
34 changed files with 3907 additions and 0 deletions
+194
View File
@@ -0,0 +1,194 @@
import { loadMessages } from "./main";
import type { Headers, ErrorResponse, User, LoginResponse, LoginRequest, RegisterRequest } from "./types";
import { API_BASE_URL } from "./config";
// Authentication and navigation handling
export let currentUser: User | null = null;
let authToken: string | null = null;
// Helper function to get auth headers
export function getAuthHeaders(): Headers {
const headers: Headers = {
'Content-Type': 'application/json',
};
if (authToken) {
headers['Authorization'] = `Bearer ${authToken}`;
}
return headers;
}
// Show login form
export function showLogin() {
document.getElementById('login-form')!.style.display = 'flex';
document.getElementById('register-form')!.style.display = 'none';
document.getElementById('chat-interface')!.style.display = 'none';
clearAlerts();
}
// Show register form
export function showRegister() {
document.getElementById('login-form')!.style.display = 'none';
document.getElementById('register-form')!.style.display = 'flex';
document.getElementById('chat-interface')!.style.display = 'none';
clearAlerts();
}
// Show chat interface
export function showChat() {
document.getElementById('login-form')!.style.display = 'none';
document.getElementById('register-form')!.style.display = 'none';
document.getElementById('chat-interface')!.style.display = 'block';
}
// Clear all alerts
export function clearAlerts() {
document.getElementById('login-alerts')!.innerHTML = '';
document.getElementById('register-alerts')!.innerHTML = '';
}
// Show alert message
export function showAlert(containerId: string, message: string, type: "success" | "danger" = 'danger') {
const container = document.getElementById(containerId)!;
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type}`;
alertDiv.textContent = message;
container.appendChild(alertDiv);
}
// Handle login form submission
document.getElementById('login-form-element')!.addEventListener('submit', async (e) => {
e.preventDefault();
const usernameElement = document.getElementById('login-username') as HTMLInputElement;
const passwordElement = document.getElementById('login-password') as HTMLInputElement;
const username = usernameElement.value.trim();
const password = passwordElement.value.trim();
if (!username || !password) {
showAlert('login-alerts', 'Пожалуйста, заполните все поля', 'danger');
return;
}
try {
const request: LoginRequest = {
username: username,
password: password
}
const response = await fetch(`${API_BASE_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request)
});
if (response.ok) {
const data: LoginResponse = await response.json();
// Store the JWT token
authToken = data.token;
currentUser = { username: data.username };
showChat();
loadMessages(); // Start loading messages
} else {
const data: ErrorResponse = await response.json();
showAlert('login-alerts', data.message || 'Неверное имя пользователя или пароль', 'danger');
}
} catch (error) {
showAlert('login-alerts', 'Ошибка соединения с сервером', 'danger');
}
});
// Handle register form submission
document.getElementById('register-form-element')!.addEventListener('submit', async (e) => {
e.preventDefault();
const usernameElement = document.getElementById('register-username') as HTMLInputElement;
const passwordElement = document.getElementById('register-password') as HTMLInputElement;
const confirmPasswordElement = document.getElementById('register-confirm-password') as HTMLInputElement;
const username = usernameElement.value.trim();
const password = passwordElement.value.trim();
const confirmPassword = confirmPasswordElement.value.trim();
if (!username || !password || !confirmPassword) {
showAlert('register-alerts', 'Пожалуйста, заполните все поля', 'danger');
return;
}
if (password !== confirmPassword) {
showAlert('register-alerts', 'Пароли не совпадают', 'danger');
return;
}
if (username.length < 3 || username.length > 20) {
showAlert('register-alerts', 'Имя пользователя должно быть от 3 до 20 символов', 'danger');
return;
}
if (password.length < 5 || password.length > 50) {
showAlert('register-alerts', 'Пароль должен быть от 5 до 50 символов', 'danger');
return;
}
try {
const request: RegisterRequest = {
username: username,
password: password,
confirm_password: confirmPassword
}
const response = await fetch(`${API_BASE_URL}/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request)
});
if (response.ok) {
// Registration successful
showAlert('register-alerts', 'Регистрация прошла успешно! Теперь вы можете войти.', 'success');
setTimeout(() => {
showLogin();
}, 2000);
} else {
const data: ErrorResponse = await response.json();
showAlert('register-alerts', data.message || 'Ошибка при регистрации', 'danger');
}
} catch (error) {
showAlert('register-alerts', 'Ошибка соединения с сервером', 'danger');
}
});
// Handle logout
export async function logout() {
try {
await fetch(`${API_BASE_URL}/logout`, {
method: 'GET',
headers: getAuthHeaders()
});
} catch (error) {
console.error('Logout error:', error);
}
currentUser = null;
authToken = null;
showLogin();
clearAlerts();
}
// Load chat interface
export function loadChat() {
showChat();
loadMessages();
}
// Check authentication status on page load
export async function checkAuthStatus() {
// For JWT, we don't have a persistent token on page load
// So we'll just show the login form
showLogin();
}
+1
View File
@@ -0,0 +1 @@
export const API_BASE_URL: string = '/api';
+40
View File
@@ -0,0 +1,40 @@
@use "common/colors" as *;
.auth-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 2rem;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
.auth-card {
background: white;
border-radius: 12px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 450px;
overflow: hidden;
transition: all 0.3s ease;
&:hover {
box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
}
}
.auth-header {
background: linear-gradient(135deg, $primary, $primary-dark);
color: white;
padding: 1.5rem;
text-align: center;
h2 {
font-size: 1.8rem;
margin-bottom: 0.5rem;
}
}
.auth-body {
padding: 2rem;
}
}
+202
View File
@@ -0,0 +1,202 @@
@use "common/colors" as *;
#chat-interface {
/* Header */
.header {
background: linear-gradient(135deg, $primary, $primary-dark);
color: white;
padding: 1rem 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
.header-content {
display: flex;
justify-content: space-between;
align-items: center;
.logo {
font-size: 1.8rem;
font-weight: 700;
display: flex;
align-items: center;
i {
margin-right: 10px;
color: $secondary;
}
}
.nav-links {
display: flex;
list-style: none;
li {
margin-left: 1.5rem;
a {
color: white;
text-decoration: none;
font-weight: 500;
transition: all 0.3s ease;
padding: 0.5rem 1rem;
border-radius: 4px;
&:hover {
background-color: rgba(255, 255, 255, 0.2);
}
}
}
}
}
}
.chat-container {
display: flex;
height: calc(100vh - 70px);
margin-top: 70px;
.chat-main {
flex: 1;
display: flex;
flex-direction: column;
background-color: #F7FAFC;
.chat-header {
padding: 1rem;
background: white;
border-bottom: 1px solid $gray;
display: flex;
align-items: center;
.chat-header-avatar {
width: 45px;
height: 45px;
border-radius: 50%;
object-fit: cover;
margin-right: 1rem;
}
.chat-header-info {
h4 {
font-size: 1.1rem;
margin-bottom: 0.2rem;
}
p {
font-size: 0.8rem;
color: #718096;
}
.online-status {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: $success;
margin-right: 5px;
}
}
}
.chat-messages {
flex: 1;
padding: 1rem;
overflow-y: auto;
.message {
margin-bottom: 1rem;
max-width: 70%;
position: relative;
.message-inner {
padding: 0.8rem 1rem;
border-radius: 12px;
position: relative;
word-wrap: break-word;
.message-time {
font-size: 0.7rem;
color: #A0AEC0;
margin-top: 0.3rem;
text-align: right;
}
}
&.received .message-inner {
background: white;
border-top-left-radius: 0;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
&.sent {
margin-left: auto;
.message-inner {
background: linear-gradient(135deg, $primary, $primary-dark);
color: white;
border-top-right-radius: 0;
}
.message-time {
color: rgba(255, 255, 255, 0.7);
}
}
}
.message-username {
font-weight: 600;
margin-bottom: 0.3rem;
font-size: 0.9rem;
}
}
.chat-input {
padding: 1rem;
background: white;
border-top: 1px solid $gray;
.input-group {
display: flex;
.message-input {
flex: 1;
padding: 0.8rem 1rem;
border: 1px solid $gray;
border-radius: 25px;
font-size: 1rem;
outline: none;
transition: all 0.3s ease;
&:focus {
border-color: $primary;
box-shadow: 0 0 0 3px rgba(108, 99, 255, 0.2);
}
}
.send-btn {
margin-left: 1rem;
width: 50px;
height: 50px;
border-radius: 50%;
background: linear-gradient(135deg, $primary, $primary-dark);
color: white;
border: none;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
&:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
}
}
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.fade-in {
animation: fadeIn 0.3s ease forwards;
}
+8
View File
@@ -0,0 +1,8 @@
$primary: #6C63FF;
$primary-dark: #564FD9;
$secondary: #FF6584;
$dark: #2D3748;
$light: #F7FAFC;
$gray: #E2E8F0;
$success: #48BB78;
$danger: #F56565;
+92
View File
@@ -0,0 +1,92 @@
@use "colors" as *;
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 15px;
}
.form-group {
margin-bottom: 1.5rem;
label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: $dark;
}
}
.form-control {
width: 100%;
padding: 0.8rem 1rem;
border: 1px solid $gray;
border-radius: 6px;
font-size: 1rem;
transition: all 0.3s ease;
&:focus {
outline: none;
border-color: $primary;
box-shadow: 0 0 0 3px rgba(108, 99, 255, 0.2);
}
}
.btn {
display: inline-block;
background: linear-gradient(135deg, $primary, $primary-dark);
color: white;
border: none;
padding: 0.8rem 1.5rem;
font-size: 1rem;
font-weight: 600;
border-radius: 6px;
cursor: pointer;
transition: all 0.3s ease;
text-align: center;
text-decoration: none;
&:hover {
background: linear-gradient(135deg, $primary-dark, $primary);
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
}
.btn-block {
display: block;
width: 100%;
}
.text-center {
text-align: center;
}
.mt-3 {
margin-top: 1rem;
}
.alert {
padding: 0.8rem 1rem;
border-radius: 6px;
margin-bottom: 1rem;
&.alert-success {
background-color: #C6F6D5;
color: #22543D;
}
&.alert-danger {
background-color: #FED7D7;
color: #742A2A;
}
}
.link {
color: $primary;
font-weight: 600;
}
button, input {
font: inherit;
}
File diff suppressed because one or more lines are too long
+199
View File
@@ -0,0 +1,199 @@
/* cyrillic-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WRhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459W1hyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WZhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WdhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WRhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459W1hyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WZhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WdhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WRhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459W1hyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WZhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WdhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WRhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459W1hyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* vietnamese */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WZhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WdhyyTh89ZNpQ.woff2) format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(/webfonts/montserrat/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
+21
View File
@@ -0,0 +1,21 @@
@use "auth";
@use "chat";
@use "common/animations";
@use "common/components";
@use "common/colors" as *;
@use "lib/fonts/montserrat";
@use "lib/font-awesome.min.css";
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Montserrat', sans-serif;
background-color: #f8f9fa;
color: $dark;
line-height: 1.6;
}
+11
View File
@@ -0,0 +1,11 @@
import { loadChat, logout, showLogin, showRegister } from "./auth";
const login = document.getElementById("login-link")!;
const register = document.getElementById("register-link")!;
const chat = document.getElementById("chat-link")!;
const logoutLink = document.getElementById("logout-link")!;
login.addEventListener("click", showLogin);
register.addEventListener("click", showRegister);
chat.addEventListener("click", loadChat);
logoutLink.addEventListener("click", logout);
+118
View File
@@ -0,0 +1,118 @@
import './css/style.scss';
import { showLogin, getAuthHeaders } from './auth';
import { API_BASE_URL } from './config';
import type { Message, Messages } from './types';
import "./links";
// Функция для форматирования времени
function formatTime(dateString: string) {
const date = new Date(dateString);
let hours = date.getHours();
let minutes = date.getMinutes();
const hoursString = hours < 10 ? '0' + hours : hours;
const minutesString = minutes < 10 ? '0' + minutes : minutes;
return hoursString + ':' + minutesString;
}
// Добавление нового сообщения в чат
export function addMessage(message: Message, isAuthor: boolean) {
const messagesContainer = document.querySelector('.chat-messages') as HTMLElement;
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isAuthor ? 'sent' : 'received'}`;
messageDiv.dataset.id = `${message.id}`;
const messageInner = document.createElement('div');
messageInner.className = 'message-inner';
if (!isAuthor) {
const usernameDiv = document.createElement('div');
usernameDiv.className = 'message-username';
usernameDiv.textContent = message.username;
messageInner.appendChild(usernameDiv);
}
const contentDiv = document.createElement('div');
contentDiv.textContent = message.content;
messageInner.appendChild(contentDiv);
const timeDiv = document.createElement('div');
timeDiv.className = 'message-time';
timeDiv.textContent = formatTime(message.timestamp);
if (isAuthor && message.is_read) {
const checkIcon = document.createElement('i');
checkIcon.className = 'fas fa-check-double';
checkIcon.style = 'margin-left: 5px; color: #48BB78;';
timeDiv.appendChild(checkIcon);
}
messageInner.appendChild(timeDiv);
messageDiv.appendChild(messageInner);
messagesContainer.appendChild(messageDiv);
// Прокрутка к новому сообщению
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
// Загрузка сообщений
export function loadMessages() {
fetch(`${API_BASE_URL}/get_messages`, {
headers: getAuthHeaders()
})
.then(response => response.json())
.then((data: Messages) => {
if (data.messages && data.messages.length > 0) {
const messagesContainer = document.querySelector('.chat-messages') as HTMLElement;
const lastMessage = messagesContainer.lastElementChild as HTMLElement
let lastMessageId: number = 0
if (lastMessage) {
lastMessageId = Number(lastMessage.dataset.id)
}
// Добавляем только новые сообщения
data.messages.forEach(msg => {
if (msg.id > lastMessageId) {
addMessage(msg, msg.is_author);
}
});
}
});
}
// Отправка сообщения
export function sendMessage() {
const input = document.querySelector('.message-input') as HTMLInputElement;
const message = input.value.trim();
if (message) {
fetch(`${API_BASE_URL}/send_message`, {
method: 'POST',
headers: getAuthHeaders(),
body: JSON.stringify({ content: message })
}).then(response => {
if (response.ok) {
input.value = '';
}
});
}
}
// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', function() {
// Настройка отправки сообщений
document.getElementById('message-form')!.addEventListener('submit', (e) => {
e.preventDefault();
sendMessage();
});
// Проверка новых сообщений каждые 2 секунды (only when chat is visible)
setInterval(() => {
if (document.getElementById('chat-interface')!.style.display !== 'none') {
loadMessages();
}
}, 2000);
showLogin();
});
+47
View File
@@ -0,0 +1,47 @@
export type Headers = {[x: string]: string}
export interface ErrorResponse {
message: string;
}
// App types
export interface Message {
id: number;
username: string;
content: string;
is_read: boolean;
is_author: boolean;
timestamp: string;
}
export interface Messages {
messages: Message[];
}
export interface User {
username: string;
}
// ----------
// API models
// ----------
// Requests
export interface LoginRequest {
username: string;
password: string;
}
export interface RegisterRequest {
username: string;
password: string;
confirm_password: string;
}
// Responses
export interface LoginResponse {
username: string;
token: string;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />