fix(frontend): исправлены дефекты P1 из аудита React (2.1-2.4)
2.1 Гонки запросов: общий механизм latest-request-wins - shared/latest-request.js (createLatestRequest) + use-latest-request.js - clientWithSignal в api-client.js: AbortSignal без правки сигнатур сервисов - ScheduleViewTab/ScheduleVersionsTab/ScheduleQualityTab/RequestDialog: устаревшие ответы не применяются, кнопки блокируются на время загрузки - смена семестра в анализе качества очищает зависимые данные 2.2 Пожелания преподавателя: semesterId=0 невозможен - resolveDefaultSemester: текущий -> ближайший будущий -> последний завершённый - явный пустой пункт «Выберите семестр», блокировка сетки/дат/переключателей - кнопка «Повторить» при ошибке метаданных 2.3 Dirty/hash-навигация: отмена возвращает URL через replaceState - confirmedHashRef + navigatingRef, hash-эффект с [role] deps 2.4 Диалог заявки: ошибка отправки показывается, диалог не закрывается - контракт onSubmitted true/false, защита от двойной отправки Тесты: latest-request.test.mjs (14 сценариев) + статические проверки в тематических тестах; всего 266 проверок, бюджеты бандлов в норме (teacher cold load 88648/90000 gzip).
This commit is contained in:
1 parent
28c3d12404
commit
9458a4a59d
19 files changed
+1261
-39
No files matched your search
@@ -76,6 +76,23 @@ export const apiClient = Object.freeze({
|
||||
)
|
||||
});
|
||||
|
||||
/**
|
||||
* Привязка AbortSignal к клиенту: каждый запрос обёртки передаёт сигнал
|
||||
* в fetch, поэтому устаревший запрос прерывается защитой от гонок
|
||||
* (см. shared/latest-request.js). Без сигнала возвращается исходный
|
||||
* клиент без обёртки.
|
||||
*/
|
||||
export function clientWithSignal(client, signal) {
|
||||
if (!signal) return client;
|
||||
const withSignal = options => ({ ...(options || {}), signal });
|
||||
return {
|
||||
get: (endpoint, options, dependencies) => client.get(endpoint, withSignal(options), dependencies),
|
||||
post: (endpoint, json, options, dependencies) => client.post(endpoint, json, withSignal(options), dependencies),
|
||||
put: (endpoint, json, options, dependencies) => client.put(endpoint, json, withSignal(options), dependencies),
|
||||
delete: (endpoint, options, dependencies) => client.delete(endpoint, withSignal(options), dependencies)
|
||||
};
|
||||
}
|
||||
|
||||
async function readResponseData(response) {
|
||||
if (response.status === 204) {
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Защита от гонок запросов (latest-request-wins).
|
||||
*
|
||||
* `begin()` прерывает предыдущий запрос и возвращает дескриптор нового:
|
||||
* монотонный `id` для проверки актуальности и `AbortSignal` для передачи
|
||||
* в apiClient. Результат разрешено применять только пока `isCurrent(id)`
|
||||
* возвращает true: любой новый `begin()` или `dispose()` делает прежний
|
||||
* запрос неактуальным, поэтому устаревший ответ не может перезаписать
|
||||
* состояние после смены фильтров или размонтирования вкладки.
|
||||
*/
|
||||
export function createLatestRequest() {
|
||||
let latestId = 0;
|
||||
let latestController = null;
|
||||
|
||||
function abortCurrent() {
|
||||
if (latestController) {
|
||||
latestController.abort();
|
||||
latestController = null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
begin() {
|
||||
abortCurrent();
|
||||
latestController = typeof AbortController === 'undefined' ? null : new AbortController();
|
||||
latestId += 1;
|
||||
return { id: latestId, signal: latestController ? latestController.signal : undefined };
|
||||
},
|
||||
isCurrent(id) {
|
||||
return id === latestId;
|
||||
},
|
||||
dispose() {
|
||||
abortCurrent();
|
||||
latestId += 1;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
import { createLatestRequest } from './latest-request.js';
|
||||
|
||||
/**
|
||||
* Гонки запросов вкладки: `begin()` запускает новый запрос и прерывает
|
||||
* предыдущий, `isCurrent(id)` разрешает применять результат только
|
||||
* последнему запуску. При размонтировании вкладки запрос прерывается
|
||||
* через `dispose()`.
|
||||
*/
|
||||
export function useLatestRequest() {
|
||||
const guardRef = useRef(null);
|
||||
if (guardRef.current === null) guardRef.current = createLatestRequest();
|
||||
|
||||
useEffect(() => () => guardRef.current.dispose(), []);
|
||||
|
||||
return guardRef.current;
|
||||
}
|
||||
Reference in new issue
Block a user