Добавлен компонент загрузочного оверлея для улучшения пользовательского опыта при проверке аутентификации в ProtectedRoute. Оптимизирована логика загрузки заметок в NotesList, чтобы избежать дублирования запросов и улучшить производительность. Обновлены стили для загрузочного оверлея и устранены лишние отступы в CSS.

This commit is contained in:
Fovway 2025-11-02 14:21:11 +07:00
parent 5c025b9349
commit 561bf35f13
4 changed files with 79 additions and 53 deletions

View File

@ -3,6 +3,7 @@ import { Navigate } from "react-router-dom";
import { useAppSelector, useAppDispatch } from "../store/hooks"; import { useAppSelector, useAppDispatch } from "../store/hooks";
import { setAuth, clearAuth } from "../store/slices/authSlice"; import { setAuth, clearAuth } from "../store/slices/authSlice";
import { authApi } from "../api/authApi"; import { authApi } from "../api/authApi";
import { LoadingOverlay } from "./common/LoadingOverlay";
export const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ export const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({
children, children,
@ -40,7 +41,7 @@ export const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({
}, [dispatch, isAuthenticated]); }, [dispatch, isAuthenticated]);
if (isChecking) { if (isChecking) {
return <div>Загрузка...</div>; return <LoadingOverlay />;
} }
return isAuthenticated ? <>{children}</> : <Navigate to="/" replace />; return isAuthenticated ? <>{children}</> : <Navigate to="/" replace />;

View File

@ -0,0 +1,11 @@
import React from "react";
export const LoadingOverlay: React.FC = () => {
return (
<div className="loading-overlay">
<div className="loading-content">
<div className="loading-text">Загрузка...</div>
</div>
</div>
);
};

View File

@ -18,70 +18,48 @@ export const NotesList = forwardRef<NotesListRef>((props, ref) => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
const { showNotification } = useNotification(); const { showNotification } = useNotification();
useEffect(() => { // Функция для загрузки данных (используется для reloadNotes)
loadNotes();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchQuery, selectedDate, selectedTag]);
const loadNotes = async () => { const loadNotes = async () => {
try { try {
let data; // Всегда загружаем все заметки для тегов и календаря
const allData = await notesApi.getAll();
let filteredAllData = allData;
if (userId) {
filteredAllData = allData.filter((note) => note.user_id === userId);
}
dispatch(setAllNotes(filteredAllData));
// Для списка заметок: если есть фильтры - делаем поисковый запрос, иначе используем все заметки
let notesData;
if (searchQuery || selectedDate || selectedTag) { if (searchQuery || selectedDate || selectedTag) {
data = await notesApi.search({ notesData = await notesApi.search({
q: searchQuery || undefined, q: searchQuery || undefined,
date: selectedDate || undefined, date: selectedDate || undefined,
tag: selectedTag || undefined, tag: selectedTag || undefined,
}); });
// Дополнительная проверка на клиенте - фильтруем по user_id на случай проблем на сервере
if (userId) {
data = data.filter((note) => note.user_id === userId);
}
dispatch(setNotes(data));
// Обновляем также все заметки для тегов и календаря
const allData = await notesApi.getAll();
if (userId) {
const filteredAllData = allData.filter(
(note) => note.user_id === userId
);
dispatch(setAllNotes(filteredAllData));
} else {
dispatch(setAllNotes(allData));
}
} else {
data = await notesApi.getAll();
// Дополнительная проверка на клиенте // Дополнительная проверка на клиенте
if (userId) { if (userId) {
data = data.filter((note) => note.user_id === userId); notesData = notesData.filter((note) => note.user_id === userId);
} }
dispatch(setNotes(data)); } else {
dispatch(setAllNotes(data)); // Сохраняем все заметки для тегов и календаря // Если нет фильтров, используем все заметки
notesData = filteredAllData;
} }
dispatch(setNotes(notesData));
} catch (error) { } catch (error) {
console.error("Ошибка загрузки заметок:", error); console.error("Ошибка загрузки заметок:", error);
showNotification("Ошибка загрузки заметок", "error"); showNotification("Ошибка загрузки заметок", "error");
} }
}; };
// Загружаем все заметки при монтировании компонента для тегов и календаря // Объединенная загрузка данных при изменении зависимостей
useEffect(() => { useEffect(() => {
const loadAllNotes = async () => {
try {
const data = await notesApi.getAll();
// Дополнительная проверка на клиенте
if (userId) { if (userId) {
const filteredData = data.filter((note) => note.user_id === userId); loadNotes();
dispatch(setAllNotes(filteredData));
} else {
dispatch(setAllNotes(data));
} }
} catch (error) { // eslint-disable-next-line react-hooks/exhaustive-deps
console.error("Ошибка загрузки всех заметок:", error); }, [userId, searchQuery, selectedDate, selectedTag]);
}
};
if (userId) {
loadAllNotes();
}
}, [dispatch, userId]);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
reloadNotes: loadNotes, reloadNotes: loadNotes,

View File

@ -560,7 +560,6 @@ header {
transition: background-color 0.3s ease, color 0.3s ease, box-shadow 0.3s ease; transition: background-color 0.3s ease, color 0.3s ease, box-shadow 0.3s ease;
} }
/* Убираем margin-top у заметок, так как gap уже обеспечивает отступы */ /* Убираем margin-top у заметок, так как gap уже обеспечивает отступы */
.notes-container .container { .notes-container .container {
margin-top: 0; margin-top: 0;
@ -4657,5 +4656,42 @@ textarea:focus {
.user-info > * { .user-info > * {
font-size: 12px; font-size: 12px;
} }
}
/* Стили для загрузочного оверлея */
.loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(2px);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.loading-content {
background-color: var(--bg-color);
padding: 20px 30px;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
display: flex;
align-items: center;
justify-content: center;
min-width: 150px;
}
.loading-text {
color: var(--text-color);
font-size: 16px;
font-weight: 500;
text-align: center;
}
/* Темная тема для загрузочного оверлея */
[data-theme="dark"] .loading-content {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.6);
} }