refactor: enforce frontend view model boundaries
Frontend verify / commits (pull_request) Successful in 28s
Frontend verify / security (pull_request) Successful in 10s
Frontend verify / verify (pull_request) Successful in 8m19s

This commit is contained in:
2026-09-28 18:48:23 +03:00
parent 5b69003516
commit ca0ad4f824
287 changed files with 8558 additions and 4538 deletions
+76 -42
View File
@@ -28,8 +28,11 @@ const accounts = [
{ id: "a", name: "Основной" },
{ id: "b", name: "ИИС" },
];
const position: Portfolio["positions"][number] = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
const position: Portfolio["positions"][number]
= {
absoluteReturn: null,
averagePurchasePrice: null,
currentValue: { currency: "RUB", value: "600" },
@@ -40,8 +43,9 @@ const position: Portfolio["positions"][number] = (/* eslint-disable unicorn/no-n
quantity: "2",
ticker: "SBER",
type: "STOCK",
}
/* eslint-enable unicorn/no-null */);
};
/* eslint-enable unicorn/no-null */
const portfolio: Portfolio = {
cashBalances: [],
isStale: false,
@@ -50,8 +54,11 @@ const portfolio: Portfolio = {
structure: { currencies: [], unvaluedCategories: [] },
totalsByCurrency: [{ currency: "RUB", value: "1200" }],
};
const receipt: BrokerageOperation = (/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
const receipt: BrokerageOperation
= {
accruedInterest: null,
category: "income",
commission: null,
@@ -67,11 +74,15 @@ const receipt: BrokerageOperation = (/* eslint-disable unicorn/no-null -- Fixtur
quantity: null,
ticker: "BOND",
type: "OPERATION_TYPE_COUPON",
}
/* eslint-enable unicorn/no-null */);
};
/* 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. */
{
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
const analytics: IncomeAnalytics
= {
accountId: "all",
bucketGranularity: "day",
buckets: [],
@@ -105,17 +116,21 @@ const analytics: IncomeAnalytics = (/* eslint-disable unicorn/no-null -- Fixture
},
],
yearComparison: null,
}
/* eslint-enable unicorn/no-null */);
};
/* eslint-enable unicorn/no-null */
const CurrentLocation: FC = () => {
const location = useLocation();
return (
<output aria-label="Текущий путь">
{location.pathname}
{location.search}
</output>
);
};
function renderPage(path: string) {
const client = createTestQueryClient();
render(
@@ -124,12 +139,14 @@ function renderPage(path: string) {
<MemoryRouter initialEntries={[path]}>
<AuthProvider>
<AppRoutes />
<CurrentLocation />
</AuthProvider>
</MemoryRouter>
</MantineProvider>
</QueryClientProvider>,
);
return client;
}
@@ -144,14 +161,17 @@ beforeEach(() => {
http.get("*/api/v1/brokerage-accounts", () =>
HttpResponse.json(
resource(
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 */))),
accounts.map(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
account =>
({
...account,
openedOn: null,
portfolioSummary: null,
type: "BROKERAGE",
}),
/* eslint-enable unicorn/no-null */
),
),
),
),
@@ -162,15 +182,17 @@ beforeEach(() => {
"*/api/v1/brokerage-accounts/:accountId/operations",
({ params }) =>
HttpResponse.json(
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
resource(
{
accountId: params.accountId,
hasNext: false,
items,
nextCursor: null,
observedAt: receipt.occurredAt,
}
/* eslint-enable unicorn/no-null */)),
},
/* eslint-enable unicorn/no-null */
),
),
),
http.get("*/api/v1/brokerage-accounts/:accountId/income-analytics", () =>
@@ -181,21 +203,24 @@ 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 */))),
events: accounts.map(
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
account =>
({
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: [],
}),
),
@@ -235,7 +260,11 @@ describe("All accounts routes", () => {
);
for (const suffix of ["operations", "income", "events"])
expect(
screen.getAllByRole("link").find(link => link.getAttribute("href") === `/accounts/all/${suffix}`),
screen
.getAllByRole("link")
.find(
link => link.getAttribute("href") === `/accounts/all/${suffix}`,
),
).toBeInTheDocument();
});
@@ -247,8 +276,10 @@ describe("All accounts routes", () => {
({ params, request }) => {
const url = new URL(request.url);
requests.push(url);
return HttpResponse.json(
resource((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
resource(
{
accountId: params.accountId,
hasNext: !url.searchParams.has("cursor"),
@@ -262,8 +293,9 @@ describe("All accounts routes", () => {
],
nextCursor: url.searchParams.has("cursor") ? null : "next",
observedAt: receipt.occurredAt,
}
/* eslint-enable unicorn/no-null */)),
},
/* eslint-enable unicorn/no-null */
),
);
},
),
@@ -281,9 +313,11 @@ describe("All accounts routes", () => {
requests.some(url => url.pathname.includes("/b/operations")),
).toBe(true),
);
const selected = requests.find(url =>
url.pathname.includes("/b/operations"),
);
expect(selected?.searchParams.get("from")).toBe("2026-08-01T00:00:00.000Z");
expect(selected?.searchParams.get("to")).toBe("2026-08-31T23:59:59.999Z");
expect(selected?.searchParams.get("categories")).toBe("income");
+6 -3
View File
@@ -62,6 +62,7 @@ describe("AppRoutes", () => {
server.use(
http.post("*/api/v1/auth/login", async ({ request }) => {
credentials = await request.json();
return HttpResponse.json({
accessToken: "login-token",
user: { email: "user@example.com", id: "user-1" },
@@ -103,7 +104,8 @@ describe("AppRoutes", () => {
),
http.get("*/api/v1/bank-cards", () => HttpResponse.json([])),
http.get("*/api/v1/bank-cards/summary", () =>
HttpResponse.json((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
HttpResponse.json(
{
cardId: null,
categories: [],
@@ -111,8 +113,9 @@ describe("AppRoutes", () => {
month: "2026-08",
net: { currency: "RUB", value: "0" },
refunds: { currency: "RUB", value: "0" },
}
/* eslint-enable unicorn/no-null */)),
},
/* eslint-enable unicorn/no-null */
),
),
);
renderRoutes("/cards?month=2026-08");
+50
View File
@@ -8,72 +8,104 @@ import { Protected, Public } from "../RouteGuards";
const CardPage = lazy(async () => {
const { CardPage } = await import("@/pages/card");
return { default: CardPage };
});
const CardsPage = lazy(async () => {
const { CardsPage } = await import("@/pages/cards");
return { default: CardsPage };
});
const BondPage = lazy(async () => {
const { BondPage } = await import("@/pages/bond");
return { default: BondPage };
});
const BondsPage = lazy(async () => {
const { BondsPage } = await import("@/pages/bonds");
return { default: BondsPage };
});
const StockPage = lazy(async () => {
const { StockPage } = await import("@/pages/stock");
return { default: StockPage };
});
const StocksPage = lazy(async () => {
const { StocksPage } = await import("@/pages/stocks");
return { default: StocksPage };
});
const AccountPage = lazy(async () => {
const { AccountPage } = await import("@/pages/account");
return { default: AccountPage };
});
const AccountEventsPage = lazy(async () => {
const { AccountEventsPage } = await import("@/pages/account-events");
return { default: AccountEventsPage };
});
const AccountOperationsPage = lazy(async () => {
const { AccountOperationsPage } = await import("@/pages/account-operations");
return { default: AccountOperationsPage };
});
const AccountIncomePage = lazy(async () => {
const { AccountIncomePage } = await import("@/pages/account-income");
return { default: AccountIncomePage };
});
const AccountsPage = lazy(async () => {
const { AccountsPage } = await import("@/pages/accounts");
return { default: AccountsPage };
});
const LoginPage = lazy(async () => {
const { LoginPage } = await import("@/pages/login");
return { default: LoginPage };
});
const NotFoundPage = lazy(async () => {
const { NotFoundPage } = await import("@/pages/not-found");
return { default: NotFoundPage };
});
const RegisterPage = lazy(async () => {
const { RegisterPage } = await import("@/pages/register");
return { default: RegisterPage };
});
const SettingsPage = lazy(async () => {
const { SettingsPage } = await import("@/pages/settings");
return { default: SettingsPage };
});
const ProtectedLayout = lazy(async () => {
const { ProtectedLayout } = await import("../ProtectedLayout");
return { default: ProtectedLayout };
});
const AppRoutes: FC = () => (
<Routes>
<Route element={<Navigate replace to="/accounts" />} path="/" />
<Route
element={(
<Public>
@@ -84,6 +116,7 @@ const AppRoutes: FC = () => (
)}
path="/login"
/>
<Route
element={(
<Public>
@@ -94,6 +127,7 @@ const AppRoutes: FC = () => (
)}
path="/register"
/>
<Route
element={(
<Protected>
@@ -111,6 +145,7 @@ const AppRoutes: FC = () => (
)}
path="/cards/:cardId"
/>
<Route
element={(
<LazyPage variant="content">
@@ -119,6 +154,7 @@ const AppRoutes: FC = () => (
)}
path="/cards"
/>
<Route
element={(
<LazyPage variant="content">
@@ -127,6 +163,7 @@ const AppRoutes: FC = () => (
)}
path="/bonds"
/>
<Route
element={(
<LazyPage variant="content">
@@ -135,6 +172,7 @@ const AppRoutes: FC = () => (
)}
path="/bonds/:bondId"
/>
<Route
element={(
<LazyPage variant="content">
@@ -143,6 +181,7 @@ const AppRoutes: FC = () => (
)}
path="/stocks"
/>
<Route
element={(
<LazyPage variant="content">
@@ -151,6 +190,7 @@ const AppRoutes: FC = () => (
)}
path="/stocks/:stockId"
/>
<Route
element={(
<LazyPage variant="content">
@@ -159,6 +199,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts"
/>
<Route
element={(
<LazyPage variant="content">
@@ -167,6 +208,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/all"
/>
<Route
element={(
<LazyPage variant="content">
@@ -175,6 +217,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/all/operations"
/>
<Route
element={(
<LazyPage variant="content">
@@ -183,6 +226,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/all/income"
/>
<Route
element={(
<LazyPage variant="content">
@@ -191,6 +235,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/all/events"
/>
<Route
element={(
<LazyPage variant="content">
@@ -199,6 +244,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/:accountId"
/>
<Route
element={(
<LazyPage variant="content">
@@ -207,6 +253,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/:accountId/events"
/>
<Route
element={(
<LazyPage variant="content">
@@ -215,6 +262,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/:accountId/income"
/>
<Route
element={(
<LazyPage variant="content">
@@ -223,6 +271,7 @@ const AppRoutes: FC = () => (
)}
path="/accounts/:accountId/operations"
/>
<Route
element={(
<LazyPage variant="content">
@@ -232,6 +281,7 @@ const AppRoutes: FC = () => (
path="/settings"
/>
</Route>
<Route
element={(
<LazyPage variant="content">
@@ -21,11 +21,13 @@ import { ProtectedDocumentTitle } from "./DocumentTitle";
const Navigation: FC = () => {
const navigate = useNavigate();
return (
<>
<button onClick={() => navigate("/accounts/all/income")} type="button">
Все счета
</button>
<button onClick={() => navigate(-1)} type="button">
Назад
</button>
@@ -39,6 +41,7 @@ const renderTitle = (path: string) =>
<MemoryRouter initialEntries={[path]}>
<AuthProvider>
<ProtectedDocumentTitle />
<Navigation />
</AuthProvider>
</MemoryRouter>
@@ -59,10 +62,13 @@ beforeEach(() => {
describe("document titles", () => {
it("updates a loading account name and follows account scope and history", async () => {
const { promise: accountsReady, resolve: resolveAccounts } = Promise.withResolvers<void>();
const { promise: accountsReady, resolve: resolveAccounts }
= Promise.withResolvers<void>();
server.use(
http.get("*/api/v1/brokerage-accounts", async () => {
await accountsReady;
return HttpResponse.json(resource([{ id: "a", name: "ИИС" }]));
}),
);
@@ -102,6 +108,7 @@ describe("document titles", () => {
server.use(
http.get("*/api/v1/stocks/by-ticker/:ticker", () => {
isRequested = true;
return HttpResponse.json({ code: "NOT_FOUND" }, { status: 404 });
}),
);
+18 -1
View File
@@ -24,29 +24,36 @@ type AccountDocumentTitleProps = {
const AccountDocumentTitle: FC<AccountDocumentTitleProps> = (props) => {
const { t } = useTranslation();
const { data } = useBrokerageAccounts();
const accountName
= props.accountId === "all"
? t("accounts.all")
: (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}`} />;
};
@@ -55,18 +62,21 @@ type InstrumentDocumentTitleProps = { identifier: string };
const BondDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
const { t } = useTranslation();
const { data } = useBond(props.identifier);
return <DocumentTitle title={data?.name ?? t("bond.instrument")} />;
};
const StockDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
const { t } = useTranslation();
const { data } = useStock(props.identifier);
return <DocumentTitle title={data?.name ?? t("stock.share")} />;
};
const CardDocumentTitle: FC<InstrumentDocumentTitleProps> = (props) => {
const { t } = useTranslation();
const { data } = useBankCard(props.identifier);
return <DocumentTitle title={data?.name ?? t("bank.card")} />;
};
@@ -94,7 +104,14 @@ const ProtectedDocumentTitle: FC = () => {
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")} />;
return settings
? (
<DocumentTitle title={t("navigation.settings")} />
)
: (
<DocumentTitle title={t("navigation.accounts")} />
);
};
export { ProtectedDocumentTitle };
+1
View File
@@ -8,6 +8,7 @@ const ProtectedLayout: FC = () => {
return (
<>
<ProtectedDocumentTitle />
<AppShell contentAboveOutlet={<AppBreadcrumbs />} />
</>
);
@@ -8,9 +8,10 @@ import { RouteErrorBoundary } from "./RouteErrorBoundary";
const session = { isAuthenticated: false };
vi.mock("@/features/auth", () => ({
useAuth: () => ((/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
{ user: session.isAuthenticated ? {} : null }
/* eslint-enable unicorn/no-null */)),
/* eslint-disable unicorn/no-null -- Fixture preserves the production contract’s explicit null values. */
useAuth: () =>
({ user: session.isAuthenticated ? {} : null }),
/* eslint-enable unicorn/no-null */
}));
const ThrowingRoute: FC = () => {
@@ -39,6 +40,7 @@ const RouteHarness: FC = () => {
<button onClick={() => navigate("/healthy")} type="button">
go healthy
</button>
<RouteErrorBoundary>
<HealthyRoute />
</RouteErrorBoundary>
@@ -62,10 +64,13 @@ describe("RouteErrorBoundary", () => {
async (path) => {
session.isAuthenticated = path === "/accounts";
let isFailing = true;
const RecoverableRoute: FC = () => {
if (isFailing) throw new Error("temporary failure");
return <div>recovered route</div>;
};
render(
<MantineProvider>
<MemoryRouter initialEntries={[path]}>
@@ -116,10 +121,12 @@ describe("RouteErrorBoundary", () => {
expect(reload).toHaveAttribute("href", "/login");
// Cancel browser navigation in JSDOM only after proving React Router did not intercept it.
let isIntercepted = true;
const preventNavigation = (event: MouseEvent) => {
isIntercepted = event.defaultPrevented;
event.preventDefault();
};
document.addEventListener("click", preventNavigation, { once: true });
fireEvent.click(reload);
expect(isIntercepted).toBe(false);
@@ -33,7 +33,13 @@ class Boundary extends Component<BoundaryProps, State> {
}
render() {
return this.state.hasError ? <RouteErrorFallback authenticated={this.props.authenticated} /> : this.props.children;
return this.state.hasError
? (
<RouteErrorFallback authenticated={this.props.authenticated} />
)
: (
this.props.children
);
}
}
@@ -46,10 +52,13 @@ const RouteErrorFallback: FC<RouteErrorFallbackProps> = (props) => {
return (
<Stack>
<Title order={1}>{t("routeError.title")}</Title>
<Text>{t("routeError.text")}</Text>
<Button component={Link} to={to}>
{t("routeError.action")}
</Button>
<Button component="a" href={to} variant="default">
{t("routeError.reload")}
</Button>
+13 -1
View File
@@ -7,7 +7,10 @@ import { useTranslation } from "react-i18next";
import { RouteTransition } from "./RouteTransition";
type LazyPageProps = PropsWithChildren<{ variant: RouteSkeletonVariant }>;
type RouteSkeletonVariant = "auth" | "content" | "shell";
type RouteSkeletonVariant = "auth"
| "content"
| "shell";
const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
const { variant } = props;
@@ -22,8 +25,11 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
role="status"
>
<Skeleton height={32} width="45%" />
<Skeleton height={48} radius="sm" />
<Skeleton height={48} radius="sm" />
<Skeleton height={36} radius="sm" />
</Stack>
</Container>
@@ -39,12 +45,16 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
>
<Group justify="space-between" p="md">
<Skeleton height={28} width={160} />
<Skeleton height={28} width={96} />
</Group>
<Container fluid p="md">
<Skeleton height={20} width="30%" />
<Stack mt="lg">
<Skeleton height={32} width="30%" />
<Skeleton height={160} radius="md" />
</Stack>
</Container>
@@ -54,6 +64,7 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
return (
<Stack aria-busy="true" aria-label={t("states.loadingTitle")} role="status">
<Skeleton height={32} width="30%" />
<Skeleton height={160} radius="md" />
</Stack>
);
@@ -61,6 +72,7 @@ const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
const LazyPage: FC<LazyPageProps> = (props) => {
const { children, variant } = props;
return (
<Suspense fallback={<RouteSkeleton variant={variant} />}>
{variant === "shell"
+6 -1
View File
@@ -11,6 +11,7 @@ const Protected: FC<PropsWithChildren> = (props) => {
const { ready, user } = useAuth();
const location = useLocation();
if (!ready) return <RouteSkeleton variant="shell" />;
return user
? (
<>{children}</>
@@ -30,13 +31,17 @@ const Public: FC<PropsWithChildren> = (props) => {
const location = useLocation();
if (!ready) return <RouteSkeleton variant="shell" />;
const requested = (location.state as null | { returnTo?: string })?.returnTo;
const requested = (location.state as null
| { returnTo?: string })?.returnTo;
const returnTo
= typeof requested === "string"
&& requested.startsWith("/")
&& !requested.startsWith("//")
? requested
: "/accounts";
return user ? <Navigate replace to={returnTo} /> : <>{children}</>;
};
+6 -4
View File
@@ -11,16 +11,18 @@ const RouteTransition: FC<PropsWithChildren> = (props) => {
const { pathname } = useLocation();
const reduceMotion = useReducedMotion();
const transition = {
duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS,
ease: "easeOut" as const,
};
return (
<LazyMotion features={domAnimation}>
<m.div
animate={{ opacity: 1 }}
initial={!reduceMotion && { opacity: 0 }}
key={pathname}
transition={{
duration: reduceMotion ? 0 : TRANSITION_DURATION_SECONDS,
ease: "easeOut",
}}
transition={transition}
>
{children}
</m.div>
@@ -8,19 +8,24 @@ import { BreadcrumbTrail } from "./BreadcrumbTrail";
type AccountBreadcrumbsProps = {
accountId: string;
section?: "events" | "income" | "operations";
section?: "events"
| "income"
| "operations";
};
const AccountBreadcrumbs: FC<AccountBreadcrumbsProps> = (props) => {
const { accountId, section } = props;
const { data: accounts } = useBrokerageAccounts();
const { t } = useTranslation();
const accountName
= accountId === "all"
? t("accounts.all")
: (accounts?.find(account => account.id === accountId)?.name
?? t("breadcrumbs.accountFallback"));
const accountPath = `/accounts/${accountId}`;
const items = [
{ label: t("breadcrumbs.accounts"), to: "/accounts" },
section ? { label: accountName, to: accountPath } : { label: accountName },
@@ -0,0 +1,25 @@
import type { FC } from "react";
import { Select } from "@mantine/core";
import { useAccountScopeSwitchVm } from "./AccountScopeSwitch.vm";
type AccountScopeSwitchProps = { accountId: string; section?: string };
const AccountScopeSwitch: FC<AccountScopeSwitchProps> = (props) => {
const { accountId, data, onChange, t } = useAccountScopeSwitchVm(props);
return (
<Select
allowDeselect={false}
data={data}
label={t("accounts.scope")}
maw={360}
onChange={onChange}
value={accountId}
w="100%"
/>
);
};
export { AccountScopeSwitch };
@@ -1,6 +1,3 @@
import type { FC } from "react";
import { Select } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router";
@@ -8,12 +5,13 @@ import { useBrokerageAccounts } from "@/entities/brokerage-account";
type AccountScopeSwitchProps = { accountId: string; section?: string };
const AccountScopeSwitch: FC<AccountScopeSwitchProps> = (props) => {
function useAccountScopeSwitchVm(props: AccountScopeSwitchProps) {
const { accountId, section } = props;
const { data: accounts } = useBrokerageAccounts();
const { t } = useTranslation();
const navigate = useNavigate();
const { search } = useLocation();
const data = [
{ label: t("accounts.all"), value: "all" },
...(accounts ?? []).map(account => ({
@@ -21,27 +19,23 @@ const AccountScopeSwitch: FC<AccountScopeSwitchProps> = (props) => {
value: account.id,
})),
];
if (data.every(item => item.value !== accountId))
data.push({ label: t("breadcrumbs.accountFallback"), value: accountId });
return (
<Select
allowDeselect={false}
data={data}
label={t("accounts.scope")}
maw={360}
onChange={(value) => {
if (!value || value === accountId) return;
const filters = new URLSearchParams(search);
filters.delete("cursor");
void navigate({
pathname: ["/accounts", encodeURIComponent(value), section].filter(Boolean).join("/"),
search: filters.toString(),
});
}}
value={accountId}
w="100%"
/>
);
};
export { AccountScopeSwitch };
const onChange: (value: null | string) => void = (value) => {
if (!value || value === accountId) return;
const filters = new URLSearchParams(search);
filters.delete("cursor");
void navigate({
pathname: ["/accounts", encodeURIComponent(value), section]
.filter(Boolean)
.join("/"),
search: filters.toString(),
});
};
return { accountId, data, onChange, t };
}
export { useAccountScopeSwitchVm };
@@ -16,6 +16,7 @@ function renderBreadcrumbs(
accounts?: { id: string; name: string }[],
) {
useBrokerageAccounts.mockReturnValue({ data: accounts });
return render(
<MantineProvider>
<MemoryRouter initialEntries={[path]}>
@@ -70,6 +71,7 @@ describe("AppBreadcrumbs", () => {
"page",
);
expect(screen.getByRole("navigation")).toHaveAttribute("data-depth", "3");
for (const separator of screen.getAllByText("→")) {
expect(separator).toHaveAttribute("aria-hidden", "true");
}
+13 -2
View File
@@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";
import { useMatch } from "react-router";
import { AccountBreadcrumbs } from "./AccountBreadcrumbs";
import { AccountScopeSwitch } from "./AccountScopeSwitch";
import { AccountScopeSwitch } from "./AccountScopeSwitch/AccountScopeSwitch";
import { BondBreadcrumbs } from "./BondBreadcrumbs";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
import { CardBreadcrumbs } from "./CardBreadcrumbs";
@@ -13,10 +13,12 @@ import { StockBreadcrumbs } from "./StockBreadcrumbs";
const AppBreadcrumbs: FC = () => {
const { t } = useTranslation();
const operations = useMatch({
end: true,
path: "/accounts/:accountId/operations",
});
const events = useMatch({ end: true, path: "/accounts/:accountId/events" });
const income = useMatch({ end: true, path: "/accounts/:accountId/income" });
const account = useMatch({ end: true, path: "/accounts/:accountId" });
@@ -37,6 +39,7 @@ const AppBreadcrumbs: FC = () => {
accountId={operations.params.accountId ?? ""}
section="operations"
/>
<AccountScopeSwitch
accountId={operations.params.accountId ?? ""}
section="operations"
@@ -50,6 +53,7 @@ const AppBreadcrumbs: FC = () => {
accountId={events.params.accountId ?? ""}
section="events"
/>
<AccountScopeSwitch
accountId={events.params.accountId ?? ""}
section="events"
@@ -63,6 +67,7 @@ const AppBreadcrumbs: FC = () => {
accountId={income.params.accountId ?? ""}
section="income"
/>
<AccountScopeSwitch
accountId={income.params.accountId ?? ""}
section="income"
@@ -73,6 +78,7 @@ const AppBreadcrumbs: FC = () => {
return (
<Stack gap={0} mb="md">
<AccountBreadcrumbs accountId={account.params.accountId ?? ""} />
<AccountScopeSwitch accountId={account.params.accountId ?? ""} />
</Stack>
);
@@ -80,7 +86,12 @@ const AppBreadcrumbs: FC = () => {
if (cards) return <BreadcrumbTrail items={[{ label: t("bank.title") }]} />;
if (accounts)
return <BreadcrumbTrail items={[{ label: t("breadcrumbs.accounts") }]} />;
return settings ? <BreadcrumbTrail items={[{ label: t("breadcrumbs.settings") }]} /> : undefined;
return settings
? (
<BreadcrumbTrail items={[{ label: t("breadcrumbs.settings") }]} />
)
: undefined;
};
export { AppBreadcrumbs };
@@ -7,9 +7,11 @@ import { useBond } from "@/entities/bond";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
type BondBreadcrumbsProps = { identifier: string };
const BondBreadcrumbs: FC<BondBreadcrumbsProps> = (props) => {
const { data } = useBond(props.identifier);
const { t } = useTranslation();
return (
<BreadcrumbTrail
items={[
@@ -7,11 +7,13 @@ import { Link } from "react-router";
import classes from "./AppBreadcrumbs.module.css";
type BreadcrumbTrailProps = { items: Crumb[] };
type Crumb = { label: string; to?: string };
const BreadcrumbTrail: FC<BreadcrumbTrailProps> = (props) => {
const { items } = props;
const { t } = useTranslation();
return (
<Breadcrumbs
aria-label={t("breadcrumbs.label")}
@@ -7,9 +7,11 @@ import { useBankCard } from "@/entities/bank-card";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
type CardBreadcrumbsProps = { identifier: string };
const CardBreadcrumbs: FC<CardBreadcrumbsProps> = (props) => {
const { data } = useBankCard(props.identifier);
const { t } = useTranslation();
return (
<BreadcrumbTrail
items={[
@@ -7,9 +7,11 @@ import { useStock } from "@/entities/stock";
import { BreadcrumbTrail } from "./BreadcrumbTrail";
type StockBreadcrumbsProps = { identifier: string };
const StockBreadcrumbs: FC<StockBreadcrumbsProps> = (props) => {
const { data } = useStock(props.identifier);
const { t } = useTranslation();
return (
<BreadcrumbTrail
items={[
-178
View File
@@ -30,31 +30,6 @@
}
}
.rubles {
pointer-events: none;
color: var(--mantine-color-green-8);
stroke: currentColor;
& path {
opacity: 0;
--flight-x: -7px;
--flight-rotation: -20deg;
--flight-delay: 0ms;
}
& path:nth-child(2) {
--flight-x: 0px;
--flight-rotation: 8deg;
--flight-delay: 120ms;
}
& path:nth-child(3) {
--flight-x: 7px;
--flight-rotation: 24deg;
--flight-delay: 240ms;
}
}
.stocksIcon {
color: var(--mantine-color-green-8);
}
@@ -67,163 +42,10 @@
color: var(--mantine-color-gray-7);
}
.portfolioRuble {
stroke: var(--mantine-color-green-8);
opacity: 0;
}
.stockArrow {
transform-origin: 21px 5px;
}
.topSlider,
.bottomSlider {
fill: var(--mantine-color-body);
}
@media (prefers-reduced-motion: no-preference) {
.navLink {
transition: background-color 180ms ease-in-out;
}
.drawStroke,
.couponLines path {
stroke-dasharray: 1;
}
.topSlider {
--slider-offset: 3px;
--slider-delay: 0ms;
}
.bottomSlider {
--slider-offset: -3px;
--slider-delay: 160ms;
}
.couponLines path:nth-child(2) {
--line-delay: 140ms;
}
.couponLines path:nth-child(3) {
--line-delay: 280ms;
}
svg[data-icon-animating] {
.rubles path {
animation: ruble-fly 800ms ease-out var(--flight-delay) both;
}
.portfolioHandle {
animation: handle-lift 1200ms ease-in-out;
}
.portfolioLid {
animation: lid-open 1200ms ease-in-out;
}
.portfolioRuble {
animation: portfolio-ruble-reveal 1200ms ease-in-out;
}
.stockArrow {
animation: arrow-pop 300ms ease-out 400ms both;
}
.couponLines path {
animation: stroke-draw 300ms ease-out var(--line-delay, 0ms) both;
}
.drawStroke {
animation: stroke-draw 450ms ease-out;
}
:is(.topSlider, .bottomSlider) {
animation: slider-slide 650ms ease-in-out var(--slider-delay) both;
}
}
}
@keyframes ruble-fly {
0% {
opacity: 0;
transform: translate(0, 4px);
}
20%,
50% {
opacity: 1;
}
100% {
opacity: 0;
transform: translate(var(--flight-x), -10px) rotate(var(--flight-rotation));
}
}
@keyframes handle-lift {
0%,
100% {
transform: translateY(0);
}
20% {
transform: translateY(-3px);
}
40%,
75% {
transform: translateY(-3px);
}
}
@keyframes lid-open {
0%,
15%,
100% {
transform: translateY(0);
}
40%,
75% {
transform: translateY(-3px);
}
}
@keyframes portfolio-ruble-reveal {
0%,
25%,
100% {
opacity: 0;
transform: translateY(2px);
}
40%,
75% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes arrow-pop {
0% {
opacity: 0;
transform: scale(0.7);
}
60% {
opacity: 1;
transform: scale(1.2);
}
100% {
opacity: 1;
transform: scale(1);
}
}
@keyframes stroke-draw {
0% {
stroke-dashoffset: 1;
}
100% {
stroke-dashoffset: 0;
}
}
@keyframes slider-slide {
0%,
100% {
transform: translateX(0);
}
50% {
transform: translateX(var(--slider-offset));
}
}
@media (max-width: 47.99375em) {
+33 -80
View File
@@ -1,11 +1,16 @@
import type { FC, ReactNode } from "react";
import { AppShell as MantineAppShell, NavLink, Text } from "@mantine/core";
import {
BondsIcon,
CardsIcon,
PortfolioIcon,
SettingsIcon,
StocksIcon,
} from "@wealthledger/icons";
import { useTranslation } from "react-i18next";
import { Outlet, NavLink as RouterNavLink, useLocation } from "react-router";
import { bindIconAnimation } from "@/shared/lib";
import classes from "./AppShell.module.css";
type AppShellProps = {
@@ -16,80 +21,34 @@ const AppShell: FC<AppShellProps> = (props) => {
const { contentAboveOutlet } = props;
const { t } = useTranslation();
const { pathname } = useLocation();
const items = [
{
icon: (
<>
<path d="M3 10v9h18v-9" />
<path className={classes.portfolioHandle} d="M8 6V4h8v2" />
<path
className={classes.portfolioLid}
d="M3 10V8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2H3Zm6 0v3h6v-3"
/>
<path
className={classes.portfolioRuble}
d="M10 18v-7h3a2 2 0 0 1 0 4H9m0 1.5h4"
/>
</>
),
icon: <PortfolioIcon size={20} />,
iconClassName: classes.portfolioIcon,
label: t("navigation.accounts"),
to: "/accounts",
},
{
icon: (
<>
<path d="M3 5h18v14H3V5Zm0 4h18M6 15h4" />
<g className={classes.rubles}>
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
<path d="M10 12V4h3a2 2 0 0 1 0 4H9m0 2h4" />
</g>
</>
),
icon: <CardsIcon size={20} />,
iconClassName: classes.cardsIcon,
label: t("navigation.cards"),
to: "/cards",
},
{
icon: (
<>
<path d="M3 3v18h18" />
<path
className={classes.drawStroke}
d="M7 14l5-5 4 3 5-7"
pathLength={1}
/>
<path className={classes.stockArrow} d="M16 5h5v5" />
</>
),
icon: <StocksIcon size={20} />,
iconClassName: classes.stocksIcon,
label: t("navigation.stocks"),
to: "/stocks",
},
{
icon: (
<>
<path d="M6 3h12v18l-3-2-3 2-3-2-3 2V3Z" />
<g className={classes.couponLines}>
<path d="M9 7h6" pathLength={1} />
<path d="M9 11h6" pathLength={1} />
<path d="M9 15h3" pathLength={1} />
</g>
</>
),
icon: <BondsIcon size={20} />,
iconClassName: classes.bondsIcon,
label: t("navigation.bonds"),
to: "/bonds",
},
{
icon: (
<>
<path d="M4 7h16M4 17h16" />
<path className={classes.topSlider} d="M10 4v6h4V4h-4Z" />
<path className={classes.bottomSlider} d="M10 14v6h4v-6h-4Z" />
</>
),
icon: <SettingsIcon size={20} />,
iconClassName: classes.settingsIcon,
label: t("navigation.settings"),
to: "/settings",
@@ -105,6 +64,7 @@ const AppShell: FC<AppShellProps> = (props) => {
<MantineAppShell.Header className={classes.header}>
<Text fw={700}>{t("appName")}</Text>
</MantineAppShell.Header>
<MantineAppShell.Navbar p="sm">
{items.map(item => (
<NavLink
@@ -117,45 +77,38 @@ const AppShell: FC<AppShellProps> = (props) => {
<span
className={`${classes.navIcon} ${item.iconClassName ?? ""}`}
>
<svg
aria-hidden="true"
fill="none"
focusable="false"
height={20}
ref={bindIconAnimation}
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="1.5"
viewBox="0 0 24 24"
width={20}
>
{item.icon}
</svg>
{item.icon}
</span>
)}
to={item.to}
/>
))}
</MantineAppShell.Navbar>
<MantineAppShell.Main className={classes.main}>
<div className={classes.content}>
{contentAboveOutlet}
<Outlet />
</div>
</MantineAppShell.Main>
<nav aria-label={t("appName")} className={classes.bottomNav}>
{items.map(item => (
<RouterNavLink
className={
(pathname.startsWith(item.to)) ? (classes.active) : undefined
}
key={item.to}
to={item.to}
>
{item.label}
</RouterNavLink>
))}
{items.map((item) => {
const appearanceClass = pathname.startsWith(item.to)
? classes.active
: undefined;
return (
<RouterNavLink
className={appearanceClass}
key={item.to}
to={item.to}
>
{item.label}
</RouterNavLink>
);
})}
</nav>
</MantineAppShell>
);