chore: finish frontend ESLint migration #18

Enable every plugin recommended preset and replace Biome with ESLint formatting.

Preserve API contracts and JSX whitespace; verify source, tests, builds and tooling.
This commit is contained in:
2026-09-28 16:36:40 +03:00
committed by ksv741
parent 57630102e4
commit 72d7835227
253 changed files with 10059 additions and 8864 deletions
+137 -119
View File
@@ -1,3 +1,5 @@
import type { FC } from "react";
import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import {
@@ -7,96 +9,104 @@ import {
screen,
waitFor,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC } from "react";
import { http, HttpResponse } from "msw";
import { MemoryRouter, useLocation } from "react-router";
import { beforeEach, describe, expect, it } from "vitest";
import type { BrokerageOperation } from "@/entities/broker-operation";
import type { IncomeAnalytics } from "@/entities/income";
import type { Portfolio } from "@/entities/portfolio";
import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes";
const accounts = [
{ id: "a", name: "Основной" },
{ id: "b", name: "ИИС" },
];
const position: Portfolio["positions"][number] = {
figi: "SBER",
displayName: "Сбербанк",
type: "STOCK",
quantity: "2",
currentValue: { currency: "RUB", value: "600" },
absoluteReturn: null,
averagePurchasePrice: null,
isin: null,
ticker: "SBER",
logoName: null,
};
const position: Portfolio["positions"][number] = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
absoluteReturn: null,
averagePurchasePrice: null,
currentValue: { currency: "RUB", value: "600" },
displayName: "Сбербанк",
figi: "SBER",
isin: null,
logoName: null,
quantity: "2",
ticker: "SBER",
type: "STOCK",
}
/* eslint-enable unicorn/no-null */);
const portfolio: Portfolio = {
lastSuccessfulAt: "2026-08-15T12:00:00Z",
isStale: false,
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
structure: { currencies: [], unvaluedCategories: [] },
cashBalances: [],
positions: accounts.map((account) => ({ ...position, account })),
isStale: false,
lastSuccessfulAt: "2026-08-15T12:00:00Z",
positions: accounts.map(account => ({ ...position, account })),
structure: { currencies: [], unvaluedCategories: [] },
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
};
const receipt: BrokerageOperation = {
id: "same",
occurredAt: "2026-08-15T12:00:00Z",
type: "OPERATION_TYPE_COUPON",
category: "income",
description: "Выплата купона",
figi: null,
instrumentUid: null,
ticker: "BOND",
instrumentType: "bond",
logoName: null,
payment: { currency: "RUB", value: "1" },
quantity: null,
price: null,
accruedInterest: null,
commission: null,
};
const items = accounts.map((account) => ({ ...receipt, account }));
const analytics: IncomeAnalytics = {
accountId: "all",
period: { from: "2026-08-01", to: "2026-08-31" },
calculatedAt: "2026-09-01T12:00:00Z",
totalsByCurrency: [
{
currency: "RUB",
coupon: { currency: "RUB", value: "2" },
dividend: { currency: "RUB", value: "0" },
total: { currency: "RUB", value: "2" },
const receipt: BrokerageOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accruedInterest: null,
category: "income",
commission: null,
description: "Выплата купона",
figi: null,
id: "same",
instrumentType: "bond",
instrumentUid: null,
logoName: null,
occurredAt: "2026-08-15T12:00:00Z",
payment: { currency: "RUB", value: "1" },
price: null,
quantity: null,
ticker: "BOND",
type: "OPERATION_TYPE_COUPON",
}
/* eslint-enable unicorn/no-null */);
const items = accounts.map(account => ({ ...receipt, account }));
const analytics: IncomeAnalytics = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: "all",
bucketGranularity: "day",
buckets: [],
calculatedAt: "2026-09-01T12:00:00Z",
entries: items.map(entry => ({ ...entry, instrumentKey: "bond:RUB" })),
instruments: [
{
coupon: { currency: "RUB", value: "2" },
displayName: "Облигация",
dividend: { currency: "RUB", value: "0" },
figi: null,
instrumentType: "bond",
instrumentUid: null,
key: "bond:RUB",
receiptCount: 2,
ticker: "BOND",
total: { currency: "RUB", value: "2" },
},
],
period: { from: "2026-08-01", to: "2026-08-31" },
previous: {
period: { from: "2026-07-01", to: "2026-07-31" },
totalsByCurrency: [],
},
],
previous: {
period: { from: "2026-07-01", to: "2026-07-31" },
totalsByCurrency: [],
},
yearComparison: null,
bucketGranularity: "day",
buckets: [],
instruments: [
{
key: "bond:RUB",
figi: null,
instrumentUid: null,
ticker: "BOND",
instrumentType: "bond",
displayName: "Облигация",
coupon: { currency: "RUB", value: "2" },
dividend: { currency: "RUB", value: "0" },
total: { currency: "RUB", value: "2" },
receiptCount: 2,
},
],
entries: items.map((entry) => ({ ...entry, instrumentKey: "bond:RUB" })),
};
totalsByCurrency: [
{
coupon: { currency: "RUB", value: "2" },
currency: "RUB",
dividend: { currency: "RUB", value: "0" },
total: { currency: "RUB", value: "2" },
},
],
yearComparison: null,
}
/* eslint-enable unicorn/no-null */);
const CurrentLocation: FC = () => {
const location = useLocation();
return (
@@ -128,18 +138,20 @@ beforeEach(() => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test",
user: { id: "user", email: "user@example.com" },
user: { email: "user@example.com", id: "user" },
}),
),
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json(
resource(
accounts.map((account) => ({
...account,
type: "BROKERAGE",
openedOn: null,
portfolioSummary: null,
})),
accounts.map(account => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
...account,
openedOn: null,
portfolioSummary: null,
type: "BROKERAGE",
}
/* eslint-enable unicorn/no-null */))),
),
),
),
@@ -150,13 +162,15 @@ beforeEach(() => {
"*/api/v1/brokerage-accounts/:accountId/operations",
({ params }) =>
HttpResponse.json(
resource({
accountId: params.accountId,
items,
hasNext: false,
nextCursor: null,
observedAt: receipt.occurredAt,
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: params.accountId,
hasNext: false,
items,
nextCursor: null,
observedAt: receipt.occurredAt,
}
/* eslint-enable unicorn/no-null */)),
),
),
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
@@ -167,20 +181,22 @@ beforeEach(() => {
resource({
accountId: "all",
calculatedAt: receipt.occurredAt,
events: accounts.map(account => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
account,
date: "2026-09-15",
dateKind: "event",
displayName: "Облигация",
figi: null,
instrumentUid: null,
isin: null,
logoName: null,
projectedAmount: { currency: "RUB", value: "2" },
ticker: "BOND",
type: "coupon",
}
/* eslint-enable unicorn/no-null */))),
incomeTotalsByCurrency: [],
events: accounts.map((account) => ({
account,
type: "coupon",
date: "2026-09-15",
dateKind: "event",
figi: null,
instrumentUid: null,
ticker: "BOND",
displayName: "Облигация",
isin: null,
logoName: null,
projectedAmount: { currency: "RUB", value: "2" },
})),
}),
),
),
@@ -219,7 +235,7 @@ describe("All accounts routes", () => {
);
for (const suffix of ["operations", "income", "events"])
expect(
document.querySelector(`a[href="/accounts/all/${suffix}"]`),
screen.getAllByRole("link").find(link => link.getAttribute("href") === `/accounts/all/${suffix}`),
).toBeInTheDocument();
});
@@ -228,24 +244,26 @@ describe("All accounts routes", () => {
server.use(
http.get(
"*/api/v1/brokerage-accounts/:accountId/operations",
({ request, params }) => {
({ params, request }) => {
const url = new URL(request.url);
requests.push(url);
return HttpResponse.json(
resource({
accountId: params.accountId,
items: [
{
...receipt,
description: url.searchParams.has("cursor")
? "Вторая страница"
: "Первая страница",
},
],
hasNext: !url.searchParams.has("cursor"),
nextCursor: url.searchParams.has("cursor") ? null : "next",
observedAt: receipt.occurredAt,
}),
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
accountId: params.accountId,
hasNext: !url.searchParams.has("cursor"),
items: [
{
...receipt,
description: url.searchParams.has("cursor")
? "Вторая страница"
: "Первая страница",
},
],
nextCursor: url.searchParams.has("cursor") ? null : "next",
observedAt: receipt.occurredAt,
}
/* eslint-enable unicorn/no-null */)),
);
},
),
@@ -260,10 +278,10 @@ describe("All accounts routes", () => {
fireEvent.click(await screen.findByRole("option", { name: "ИИС" }));
await waitFor(() =>
expect(
requests.some((url) => url.pathname.includes("/b/operations")),
requests.some(url => url.pathname.includes("/b/operations")),
).toBe(true),
);
const selected = requests.find((url) =>
const selected = requests.find(url =>
url.pathname.includes("/b/operations"),
);
expect(selected?.searchParams.get("from")).toBe("2026-08-01T00:00:00.000Z");
@@ -286,8 +304,8 @@ describe("All accounts routes", () => {
: HttpResponse.json(
resource({
accountId: "all",
items,
hasNext: true,
items,
nextCursor: "expired",
observedAt: receipt.occurredAt,
}),
@@ -305,7 +323,7 @@ describe("All accounts routes", () => {
});
it("retains the complete portfolio during a failed refresh", async () => {
const client = renderPage("/accounts/all");
const view = renderPage("/accounts/all");
await screen.findAllByText("Сбербанк");
server.use(
http.get("*/api/v1/brokerage-accounts/all/portfolio", () =>
@@ -313,7 +331,7 @@ describe("All accounts routes", () => {
),
);
await act(() =>
client.invalidateQueries({
view.invalidateQueries({
predicate: ({ queryKey }) => String(queryKey[1]).endsWith("/portfolio"),
}),
);
+33 -29
View File
@@ -2,32 +2,34 @@ import { MantineProvider } from "@mantine/core";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen } from "@testing-library/react";
import { cssVariablesResolver, theme } from "@wealthledger/ui/theme";
import { HttpResponse, http } from "msw";
import { http, HttpResponse } from "msw";
import { MemoryRouter } from "react-router";
import { describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query";
import { server } from "@/test/server";
import { AppRoutes } from "./AppRoutes";
describe("AppRoutes", () => {
function renderRoutes(path: string) {
return render(
<QueryClientProvider client={createTestQueryClient()}>
<MemoryRouter initialEntries={[path]}>
<MantineProvider
cssVariablesResolver={cssVariablesResolver}
theme={theme}
>
<AuthProvider>
<AppRoutes />
</AuthProvider>
</MantineProvider>
</MemoryRouter>
</QueryClientProvider>,
);
}
function renderRoutes(path: string) {
return render(
<QueryClientProvider client={createTestQueryClient()}>
<MemoryRouter initialEntries={[path]}>
<MantineProvider
cssVariablesResolver={cssVariablesResolver}
theme={theme}
>
<AuthProvider>
<AppRoutes />
</AuthProvider>
</MantineProvider>
</MemoryRouter>
</QueryClientProvider>,
);
}
describe("AppRoutes", () => {
it.each([
["/", "Вход"],
["/login", "Вход"],
@@ -62,7 +64,7 @@ describe("AppRoutes", () => {
credentials = await request.json();
return HttpResponse.json({
accessToken: "login-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
});
}),
);
@@ -96,19 +98,21 @@ describe("AppRoutes", () => {
http.post("*/api/v1/auth/login", () =>
HttpResponse.json({
accessToken: "test",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
http.get("*/api/v1/bank-cards", () => HttpResponse.json([])),
http.get("*/api/v1/bank-cards/summary", () =>
HttpResponse.json({
month: "2026-08",
cardId: null,
expenses: { currency: "RUB", value: "0" },
refunds: { currency: "RUB", value: "0" },
net: { currency: "RUB", value: "0" },
categories: [],
}),
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
cardId: null,
categories: [],
expenses: { currency: "RUB", value: "0" },
month: "2026-08",
net: { currency: "RUB", value: "0" },
refunds: { currency: "RUB", value: "0" },
}
/* eslint-enable unicorn/no-null */)),
),
);
renderRoutes("/cards?month=2026-08");
@@ -132,7 +136,7 @@ describe("AppRoutes", () => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
);
+62 -60
View File
@@ -1,6 +1,8 @@
import type { FC } from "react";
import { lazy } from "react";
import { Navigate, Route, Routes } from "react-router";
import { LazyPage } from "../RouteFallback";
import { Protected, Public } from "../RouteGuards";
@@ -71,172 +73,172 @@ const ProtectedLayout = lazy(async () => {
const AppRoutes: FC = () => (
<Routes>
<Route path="/" element={<Navigate to="/accounts" replace />} />
<Route element={<Navigate replace to="/accounts" />} path="/" />
<Route
path="/login"
element={
element={(
<Public>
<LazyPage variant="auth">
<LoginPage />
</LazyPage>
</Public>
}
)}
path="/login"
/>
<Route
path="/register"
element={
element={(
<Public>
<LazyPage variant="auth">
<RegisterPage />
</LazyPage>
</Public>
}
)}
path="/register"
/>
<Route
element={
element={(
<Protected>
<LazyPage variant="shell">
<ProtectedLayout />
</LazyPage>
</Protected>
}
)}
>
<Route
path="/cards/:cardId"
element={
element={(
<LazyPage variant="content">
<CardPage />
</LazyPage>
}
)}
path="/cards/:cardId"
/>
<Route
path="/cards"
element={
element={(
<LazyPage variant="content">
<CardsPage />
</LazyPage>
}
)}
path="/cards"
/>
<Route
path="/bonds"
element={
element={(
<LazyPage variant="content">
<BondsPage />
</LazyPage>
}
)}
path="/bonds"
/>
<Route
path="/bonds/:bondId"
element={
element={(
<LazyPage variant="content">
<BondPage />
</LazyPage>
}
)}
path="/bonds/:bondId"
/>
<Route
path="/stocks"
element={
element={(
<LazyPage variant="content">
<StocksPage />
</LazyPage>
}
)}
path="/stocks"
/>
<Route
path="/stocks/:stockId"
element={
element={(
<LazyPage variant="content">
<StockPage />
</LazyPage>
}
)}
path="/stocks/:stockId"
/>
<Route
path="/accounts"
element={
element={(
<LazyPage variant="content">
<AccountsPage />
</LazyPage>
}
)}
path="/accounts"
/>
<Route
path="/accounts/all"
element={
element={(
<LazyPage variant="content">
<AccountPage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all"
/>
<Route
path="/accounts/all/operations"
element={
element={(
<LazyPage variant="content">
<AccountOperationsPage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all/operations"
/>
<Route
path="/accounts/all/income"
element={
element={(
<LazyPage variant="content">
<AccountIncomePage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all/income"
/>
<Route
path="/accounts/all/events"
element={
element={(
<LazyPage variant="content">
<AccountEventsPage accountId="all" />
</LazyPage>
}
)}
path="/accounts/all/events"
/>
<Route
path="/accounts/:accountId"
element={
element={(
<LazyPage variant="content">
<AccountPage />
</LazyPage>
}
)}
path="/accounts/:accountId"
/>
<Route
path="/accounts/:accountId/events"
element={
element={(
<LazyPage variant="content">
<AccountEventsPage />
</LazyPage>
}
)}
path="/accounts/:accountId/events"
/>
<Route
path="/accounts/:accountId/income"
element={
element={(
<LazyPage variant="content">
<AccountIncomePage />
</LazyPage>
}
)}
path="/accounts/:accountId/income"
/>
<Route
path="/accounts/:accountId/operations"
element={
element={(
<LazyPage variant="content">
<AccountOperationsPage />
</LazyPage>
}
)}
path="/accounts/:accountId/operations"
/>
<Route
path="/settings"
element={
element={(
<LazyPage variant="content">
<SettingsPage />
</LazyPage>
}
)}
path="/settings"
/>
</Route>
<Route
path="*"
element={
element={(
<LazyPage variant="content">
<NotFoundPage />
</LazyPage>
}
)}
path="*"
/>
</Routes>
);
@@ -1,3 +1,5 @@
import type { FC } from "react";
import { QueryClientProvider } from "@tanstack/react-query";
import {
act,
@@ -6,24 +8,25 @@ import {
screen,
waitFor,
} from "@testing-library/react";
import { HttpResponse, http } from "msw";
import type { FC } from "react";
import { http, HttpResponse } from "msw";
import { MemoryRouter, useNavigate } from "react-router";
import { beforeEach, describe, expect, it } from "vitest";
import { AuthProvider } from "@/features/auth";
import { createTestQueryClient } from "@/test/query";
import { resource } from "@/test/resource";
import { server } from "@/test/server";
import { ProtectedDocumentTitle } from "./DocumentTitle";
const Navigation: FC = () => {
const navigate = useNavigate();
return (
<>
<button type="button" onClick={() => navigate("/accounts/all/income")}>
<button onClick={() => navigate("/accounts/all/income")} type="button">
Все счета
</button>
<button type="button" onClick={() => navigate(-1)}>
<button onClick={() => navigate(-1)} type="button">
Назад
</button>
</>
@@ -48,7 +51,7 @@ beforeEach(() => {
http.post("*/api/v1/auth/refresh", () =>
HttpResponse.json({
accessToken: "test-token",
user: { id: "user-1", email: "user@example.com" },
user: { email: "user@example.com", id: "user-1" },
}),
),
);
@@ -56,10 +59,7 @@ beforeEach(() => {
describe("document titles", () => {
it("updates a loading account name and follows account scope and history", async () => {
let resolveAccounts!: () => void;
const accountsReady = new Promise<void>((resolve) => {
resolveAccounts = resolve;
});
const { promise: accountsReady, resolve: resolveAccounts } = Promise.withResolvers<void>();
server.use(
http.get("*/api/v1/brokerage-accounts", async () => {
await accountsReady;
@@ -68,7 +68,7 @@ describe("document titles", () => {
);
renderTitle("/accounts/a/income?from=2026-01-01&to=2026-08-31");
expect(document.title).toBe("Пассивный доход — Счет — WealthLedger");
await act(async () => resolveAccounts());
await act(() => Promise.resolve(resolveAccounts()));
await waitFor(() =>
expect(document.title).toBe("Пассивный доход — ИИС — WealthLedger"),
);
@@ -98,15 +98,15 @@ describe("document titles", () => {
);
it("keeps a useful title when the instrument is unavailable", async () => {
let requested = false;
let isRequested = false;
server.use(
http.get("*/api/v1/stocks/by-ticker/:ticker", () => {
requested = true;
isRequested = true;
return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 });
}),
);
renderTitle("/stocks/missing");
await waitFor(() => expect(requested).toBe(true));
await waitFor(() => expect(isRequested).toBe(true));
expect(document.title).toBe("Акция — WealthLedger");
});
});
+30 -30
View File
@@ -1,7 +1,9 @@
import { useDocumentTitle } from "@mantine/hooks";
import type { FC } from "react";
import { useDocumentTitle } from "@mantine/hooks";
import { useTranslation } from "react-i18next";
import { useMatch } from "react-router";
import { useBankCard } from "@/entities/bank-card";
import { useBond } from "@/entities/bond";
import { useBrokerageAccounts } from "@/entities/brokerage-account";
@@ -9,10 +11,9 @@ import { useStock } from "@/entities/stock";
type DocumentTitleProps = { title: string };
const DocumentTitle: FC<DocumentTitleProps> = (props) => {
const DocumentTitle: FC<DocumentTitleProps> = (props): undefined => {
const { t } = useTranslation();
useDocumentTitle(`${props.title} — ${t("appName")}`);
return null;
};
type AccountDocumentTitleProps = {
@@ -23,19 +24,29 @@ type AccountDocumentTitleProps = {
const AccountDocumentTitle: FC<AccountDocumentTitleProps> = (props) => {
const { t } = useTranslation();
const { data } = useBrokerageAccounts();
const accountName =
props.accountId === "all"
const accountName
= props.accountId === "all"
? t("accounts.all")
: (data?.find((account) => account.id === props.accountId)?.name ??
t("account.title"));
const section =
props.section === "income"
? t("income.title")
: props.section === "operations"
? t("ledger.title")
: props.section === "events"
? t("events.title")
: t("portfolio.title");
: (data?.find(account => account.id === props.accountId)?.name
?? t("account.title"));
let section = t("portfolio.title");
switch (props.section ?? "") {
case "income": {
section = t("income.title");
break;
}
case "operations": {
section = t("ledger.title");
break;
}
case "events": {
section = t("events.title");
break;
}
default: {
break;
}
}
return <DocumentTitle title={`${section} — ${accountName}`} />;
};
@@ -80,21 +91,10 @@ const ProtectedDocumentTitle: FC = () => {
if (bond) return <BondDocumentTitle identifier={bond.params.bondId ?? ""} />;
if (stock)
return <StockDocumentTitle identifier={stock.params.stockId ?? ""} />;
return (
<DocumentTitle
title={t(
cards
? "navigation.cards"
: bonds
? "navigation.bonds"
: stocks
? "navigation.stocks"
: settings
? "navigation.settings"
: "navigation.accounts",
)}
/>
);
if (cards) return <DocumentTitle title={t("navigation.cards")} />;
if (bonds) return <DocumentTitle title={t("navigation.bonds")} />;
if (stocks) return <DocumentTitle title={t("navigation.stocks")} />;
return settings ? <DocumentTitle title={t("navigation.settings")} /> : <DocumentTitle title={t("navigation.accounts")} />;
};
export { ProtectedDocumentTitle };
+2
View File
@@ -1,5 +1,7 @@
import type { FC } from "react";
import { AppBreadcrumbs, AppShell } from "@/app/ui";
import { ProtectedDocumentTitle } from "./DocumentTitle/DocumentTitle";
const ProtectedLayout: FC = () => {
@@ -3,11 +3,14 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { type FC, lazy, Suspense } from "react";
import { MemoryRouter, useLocation, useNavigate } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { RouteErrorBoundary } from "./RouteErrorBoundary";
let authenticated = false;
const session = { isAuthenticated: false };
vi.mock("@/features/auth", () => ({
useAuth: () => ({ user: authenticated ? {} : null }),
useAuth: () => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ user: session.isAuthenticated ? {} : null }
/* eslint-enable unicorn/no-null */)),
}));
const ThrowingRoute: FC = () => {
@@ -17,11 +20,13 @@ const ThrowingRoute: FC = () => {
const HealthyRoute: FC = () => {
return (
<div>
{useLocation().pathname === "/healthy" ? (
"healthy route"
) : (
<ThrowingRoute />
)}
{useLocation().pathname === "/healthy"
? (
"healthy route"
)
: (
<ThrowingRoute />
)}
</div>
);
};
@@ -31,7 +36,7 @@ const RouteHarness: FC = () => {
return (
<>
<button type="button" onClick={() => navigate("/healthy")}>
<button onClick={() => navigate("/healthy")} type="button">
go healthy
</button>
<RouteErrorBoundary>
@@ -55,10 +60,10 @@ describe("RouteErrorBoundary", () => {
it.each(["/accounts", "/login"])(
"recovers a transient failure through the fallback on %s itself",
async (path) => {
authenticated = path === "/accounts";
let failing = true;
session.isAuthenticated = path === "/accounts";
let isFailing = true;
const RecoverableRoute: FC = () => {
if (failing) throw new Error("temporary failure");
if (isFailing) throw new Error("temporary failure");
return <div>recovered route</div>;
};
render(
@@ -71,14 +76,14 @@ describe("RouteErrorBoundary", () => {
</MantineProvider>,
);
const action = screen.getByRole("link", { name: "Продолжить" });
failing = false;
isFailing = false;
fireEvent.click(action);
expect(await screen.findByText("recovered route")).toBeInTheDocument();
},
);
it("keeps a persistent failure recoverable without an automatic reset loop", () => {
authenticated = true;
session.isAuthenticated = true;
renderBoundary("/accounts");
fireEvent.click(screen.getByRole("link", { name: "Продолжить" }));
expect(
@@ -91,7 +96,7 @@ describe("RouteErrorBoundary", () => {
});
it("offers document navigation when React.lazy caches a rejected chunk", async () => {
authenticated = false;
session.isAuthenticated = false;
const load = vi.fn(() => Promise.reject(new Error("chunk failed")));
const Chunk = lazy(load);
render(
@@ -110,18 +115,18 @@ describe("RouteErrorBoundary", () => {
const reload = screen.getByRole("link", { name: "Перезагрузить страницу" });
expect(reload).toHaveAttribute("href", "/login");
// Cancel browser navigation in JSDOM only after proving React Router did not intercept it.
let intercepted = true;
let isIntercepted = true;
const preventNavigation = (event: MouseEvent) => {
intercepted = event.defaultPrevented;
isIntercepted = event.defaultPrevented;
event.preventDefault();
};
document.addEventListener("click", preventNavigation, { once: true });
fireEvent.click(reload);
expect(intercepted).toBe(false);
expect(isIntercepted).toBe(false);
});
it("offers login after a public route error without error details", () => {
authenticated = false;
session.isAuthenticated = false;
renderBoundary("/login");
expect(document.title).toBe("Не удалось открыть страницу — WealthLedger");
expect(screen.getByRole("link", { name: "Продолжить" })).toHaveAttribute(
@@ -132,9 +137,9 @@ describe("RouteErrorBoundary", () => {
});
it("offers accounts after a protected route error and resets on navigation", async () => {
authenticated = true;
session.isAuthenticated = true;
renderBoundary("/accounts");
screen.getByRole("button", { name: "go healthy" }).click();
fireEvent.click(screen.getByRole("button", { name: "go healthy" }));
expect(await screen.findByText("healthy route")).toBeInTheDocument();
});
});
@@ -1,14 +1,16 @@
import type { FC, PropsWithChildren } from "react";
import { Button, Stack, Text, Title } from "@mantine/core";
import { useDocumentTitle } from "@mantine/hooks";
import type { FC, PropsWithChildren } from "react";
import { Component } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
type BoundaryProps = PropsWithChildren<{
routeKey: string;
authenticated: boolean;
routeKey: string;
}>;
type RouteErrorFallbackProps = {
@@ -18,12 +20,12 @@ type RouteErrorFallbackProps = {
type State = { hasError: boolean };
class Boundary extends Component<BoundaryProps, State> {
state: State = { hasError: false };
static getDerivedStateFromError(): State {
return { hasError: true };
}
state: State = { hasError: false };
componentDidUpdate(previousProps: BoundaryProps) {
if (previousProps.routeKey !== this.props.routeKey && this.state.hasError) {
this.setState({ hasError: false });
@@ -31,10 +33,7 @@ class Boundary extends Component<BoundaryProps, State> {
}
render() {
if (this.state.hasError) {
return <RouteErrorFallback authenticated={this.props.authenticated} />;
}
return this.props.children;
return this.state.hasError ? <RouteErrorFallback authenticated={this.props.authenticated} /> : this.props.children;
}
}
@@ -60,7 +59,7 @@ const RouteErrorFallback: FC<RouteErrorFallbackProps> = (props) => {
const RouteErrorBoundary: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { pathname, search, key } = useLocation();
const { key, pathname, search } = useLocation();
const { user } = useAuth();
return (
+12 -8
View File
@@ -1,11 +1,13 @@
import { Container, Group, Skeleton, Stack } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
import { Container, Group, Skeleton, Stack } from "@mantine/core";
import { Suspense } from "react";
import { useTranslation } from "react-i18next";
import { RouteTransition } from "./RouteTransition";
type RouteSkeletonVariant = "auth" | "content" | "shell";
type LazyPageProps = PropsWithChildren<{ variant: RouteSkeletonVariant }>;
type RouteSkeletonVariant = "auth" | "content" | "shell";
const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
const { variant } = props;
@@ -13,7 +15,7 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
if (variant === "auth")
return (
<Container size={420} py="xl">
<Container py="xl" size={420}>
<Stack
aria-busy="true"
aria-label={t("states.loadingTitle")}
@@ -61,11 +63,13 @@ const LazyPage: FC<LazyPageProps> = (props) => {
const { children, variant } = props;
return (
<Suspense fallback={<RouteSkeleton variant={variant} />}>
{variant === "shell" ? (
children
) : (
<RouteTransition>{children}</RouteTransition>
)}
{variant === "shell"
? (
children
)
: (
<RouteTransition>{children}</RouteTransition>
)}
</Suspense>
);
};
+24 -18
View File
@@ -1,37 +1,43 @@
import type { FC, PropsWithChildren } from "react";
import { Navigate, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
import { RouteSkeleton } from "./RouteFallback";
const Protected: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { user, ready } = useAuth();
const { ready, user } = useAuth();
const location = useLocation();
if (!ready) return <RouteSkeleton variant="shell" />;
return user ? (
children
) : (
<Navigate
to="/login"
state={{ returnTo: `${location.pathname}${location.search}` }}
replace
/>
);
return user
? (
<>{children}</>
)
: (
<Navigate
replace
state={{ returnTo: `${location.pathname}${location.search}` }}
to="/login"
/>
);
};
const Public: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { user, ready } = useAuth();
const { ready, user } = useAuth();
const location = useLocation();
const requested = (location.state as { returnTo?: string } | null)?.returnTo;
const returnTo =
typeof requested === "string" &&
requested.startsWith("/") &&
!requested.startsWith("//")
if (!ready) return <RouteSkeleton variant="shell" />;
const requested = (location.state as null | { returnTo?: string })?.returnTo;
const returnTo
= typeof requested === "string"
&& requested.startsWith("/")
&& !requested.startsWith("//")
? requested
: "/accounts";
if (!ready) return <RouteSkeleton variant="shell" />;
return user ? <Navigate to={returnTo} replace /> : children;
return user ? <Navigate replace to={returnTo} /> : <>{children}</>;
};
export { Protected, Public };
+4 -3
View File
@@ -1,6 +1,7 @@
import type { FC, PropsWithChildren } from "react";
import { domAnimation, LazyMotion, useReducedMotion } from "motion/react";
import * as m from "motion/react-m";
import type { FC, PropsWithChildren } from "react";
import { useLocation } from "react-router";
const TRANSITION_DURATION_SECONDS = 0.2;
@@ -13,9 +14,9 @@ const RouteTransition: FC<PropsWithChildren> = (props) => {
return (
<LazyMotion features={domAnimation}>
<m.div
key={pathname}
initial={reduceMotion ? false : { opacity: 0 }}
animate={{ opacity: 1 }}
initial={!reduceMotion && { opacity: 0 }}
key={pathname}
transition={{
duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS,
ease: "easeOut",