feat: replace loading spinners with skeletons

This commit is contained in:
2026-08-27 21:43:57 +03:00
parent 7d748a65d3
commit 71a214d7ad
15 changed files with 204 additions and 58 deletions
+2
View File
@@ -6,6 +6,8 @@
Запросные экраны без успешных данных выбирают состояние в порядке loading, error, empty, loaded. Если query уже содержит данные, они остаются видимыми при фоновом refetch и его ошибке: рядом показываются неблокирующий progress и локальное предупреждение с retry. Такое состояние называется Client Cached Snapshot; оно не заменяет доменное server-side stale/fallback состояние. Запросные экраны без успешных данных выбирают состояние в порядке loading, error, empty, loaded. Если query уже содержит данные, они остаются видимыми при фоновом refetch и его ошибке: рядом показываются неблокирующий progress и локальное предупреждение с retry. Такое состояние называется Client Cached Snapshot; оно не заменяет доменное server-side stale/fallback состояние.
Initial loading без доступного результата использует page-owned structural skeleton, повторяющий semantic regions экрана (heading, cards, filters, summaries или rows), а не `StateView` или отдельный spinner. Partial loading принадлежит section view и занимает только ещё не загруженный блок. Skeleton region имеет доступное busy-обозначение, но его декоративные shapes не содержат данных, не интерактивны и не получают фокус. Route fallback сохраняет доступный application shell и skeleton-изирует content area; до auth `ready` public и protected guards показывают neutral shell skeleton. Button `loading` для mutation и compact progress при Client Cached Snapshot остаются контекстными indicators и не заменяются skeleton.
Для finance-экранов используется граница `container -> ViewModel -> view`. Для finance-экранов используется граница `container -> ViewModel -> view`.
`*.tsx` без суффикса — container: он вызывает единственный page VM hook и `*.tsx` без суффикса — container: он вызывает единственный page VM hook и
выбирает top-level Loading/Error/Empty/Loaded view. `*.vm.ts` владеет data выбирает top-level Loading/Error/Empty/Loaded view. `*.vm.ts` владеет data
+76 -15
View File
@@ -1,6 +1,7 @@
import { Loader } from "@mantine/core"; import { Container, Group, Skeleton, Stack } from "@mantine/core";
import type { FC, PropsWithChildren } from "react"; import type { FC, PropsWithChildren } from "react";
import { lazy, Suspense } from "react"; import { lazy, Suspense } from "react";
import { useTranslation } from "react-i18next";
import { Navigate, Route, Routes, useLocation } from "react-router"; import { Navigate, Route, Routes, useLocation } from "react-router";
import { useAuth } from "@/features/auth"; import { useAuth } from "@/features/auth";
@@ -41,17 +42,77 @@ const ProtectedLayout = lazy(async () => {
return { default: ProtectedLayout }; return { default: ProtectedLayout };
}); });
const LazyPage: FC<PropsWithChildren> = (props) => { type RouteSkeletonVariant = "auth" | "content" | "shell";
const { children } = props;
return <Suspense fallback={<Loader />}>{children}</Suspense>; type LazyPageProps = PropsWithChildren<{
variant: RouteSkeletonVariant;
}>;
const RouteSkeleton: FC<{ variant: RouteSkeletonVariant }> = (props) => {
const { variant } = props;
const { t } = useTranslation();
if (variant === "auth")
return (
<Container size={420} py="xl">
<Stack
aria-busy="true"
aria-label={t("states.loadingTitle")}
role="status"
>
<Skeleton height={32} width="45%" />
<Skeleton height={48} radius="sm" />
<Skeleton height={48} radius="sm" />
<Skeleton height={36} radius="sm" />
</Stack>
</Container>
);
if (variant === "shell")
return (
<Stack
aria-busy="true"
aria-label={t("states.loadingTitle")}
gap={0}
role="status"
>
<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>
</Stack>
);
return (
<Stack aria-busy="true" aria-label={t("states.loadingTitle")} role="status">
<Skeleton height={32} width="30%" />
<Skeleton height={160} radius="md" />
</Stack>
);
};
const LazyPage: FC<LazyPageProps> = (props) => {
const { children, variant } = props;
return (
<Suspense fallback={<RouteSkeleton variant={variant} />}>
{children}
</Suspense>
);
}; };
const Protected: FC<PropsWithChildren> = (props) => { const Protected: FC<PropsWithChildren> = (props) => {
const { children } = props; const { children } = props;
const { user, ready } = useAuth(); const { user, ready } = useAuth();
const location = useLocation(); const location = useLocation();
if (!ready) return null; if (!ready) return <RouteSkeleton variant="shell" />;
return user ? ( return user ? (
children children
) : ( ) : (
@@ -66,7 +127,7 @@ const Protected: FC<PropsWithChildren> = (props) => {
const Public: FC<PropsWithChildren> = (props) => { const Public: FC<PropsWithChildren> = (props) => {
const { children } = props; const { children } = props;
const { user, ready } = useAuth(); const { user, ready } = useAuth();
if (!ready) return null; if (!ready) return <RouteSkeleton variant="shell" />;
return user ? <Navigate to="/accounts" replace /> : children; return user ? <Navigate to="/accounts" replace /> : children;
}; };
@@ -78,7 +139,7 @@ const AppRoutes: FC = () => {
path="/login" path="/login"
element={ element={
<Public> <Public>
<LazyPage> <LazyPage variant="auth">
<LoginPage /> <LoginPage />
</LazyPage> </LazyPage>
</Public> </Public>
@@ -88,7 +149,7 @@ const AppRoutes: FC = () => {
path="/register" path="/register"
element={ element={
<Public> <Public>
<LazyPage> <LazyPage variant="auth">
<RegisterPage /> <RegisterPage />
</LazyPage> </LazyPage>
</Public> </Public>
@@ -97,7 +158,7 @@ const AppRoutes: FC = () => {
<Route <Route
element={ element={
<Protected> <Protected>
<LazyPage> <LazyPage variant="shell">
<ProtectedLayout /> <ProtectedLayout />
</LazyPage> </LazyPage>
</Protected> </Protected>
@@ -106,7 +167,7 @@ const AppRoutes: FC = () => {
<Route <Route
path="/accounts" path="/accounts"
element={ element={
<LazyPage> <LazyPage variant="content">
<AccountsPage /> <AccountsPage />
</LazyPage> </LazyPage>
} }
@@ -114,7 +175,7 @@ const AppRoutes: FC = () => {
<Route <Route
path="/accounts/:accountId" path="/accounts/:accountId"
element={ element={
<LazyPage> <LazyPage variant="content">
<AccountPage /> <AccountPage />
</LazyPage> </LazyPage>
} }
@@ -122,7 +183,7 @@ const AppRoutes: FC = () => {
<Route <Route
path="/accounts/:accountId/events" path="/accounts/:accountId/events"
element={ element={
<LazyPage> <LazyPage variant="content">
<AccountEventsPage /> <AccountEventsPage />
</LazyPage> </LazyPage>
} }
@@ -130,7 +191,7 @@ const AppRoutes: FC = () => {
<Route <Route
path="/accounts/:accountId/operations" path="/accounts/:accountId/operations"
element={ element={
<LazyPage> <LazyPage variant="content">
<AccountOperationsPage /> <AccountOperationsPage />
</LazyPage> </LazyPage>
} }
@@ -138,7 +199,7 @@ const AppRoutes: FC = () => {
<Route <Route
path="/settings" path="/settings"
element={ element={
<LazyPage> <LazyPage variant="content">
<SettingsPage /> <SettingsPage />
</LazyPage> </LazyPage>
} }
@@ -147,7 +208,7 @@ const AppRoutes: FC = () => {
<Route <Route
path="*" path="*"
element={ element={
<LazyPage> <LazyPage variant="content">
<NotFoundPage /> <NotFoundPage />
</LazyPage> </LazyPage>
} }
@@ -14,7 +14,10 @@ describe("TbankConnectionSection state views", () => {
<TbankConnectionLoading /> <TbankConnectionLoading />
</MantineProvider>, </MantineProvider>,
); );
expect(screen.getByText("Пожалуйста, подождите.")).toBeInTheDocument(); expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute(
"aria-busy",
"true",
);
rerender( rerender(
<MantineProvider> <MantineProvider>
<TbankConnectionError retry={retry} /> <TbankConnectionError retry={retry} />
@@ -1,6 +1,7 @@
import { Alert, Button, Text } from "@mantine/core"; import { Alert, Button, Skeleton } from "@mantine/core";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { LoadingSkeleton } from "@/shared/ui";
type TbankConnectionErrorProps = { type TbankConnectionErrorProps = {
retry: () => void; retry: () => void;
@@ -8,7 +9,13 @@ type TbankConnectionErrorProps = {
const TbankConnectionLoading: FC = () => { const TbankConnectionLoading: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
return <Text>{t("states.loadingText")}</Text>;
return (
<LoadingSkeleton label={t("states.loadingTitle")}>
<Skeleton height={20} width="45%" />
<Skeleton height={36} width={140} radius="sm" />
</LoadingSkeleton>
);
}; };
const TbankConnectionError: FC<TbankConnectionErrorProps> = (props) => { const TbankConnectionError: FC<TbankConnectionErrorProps> = (props) => {
@@ -94,4 +94,19 @@ describe("AccountEventsPage", () => {
screen.getByRole("button", { name: "Повторить" }).click(); screen.getByRole("button", { name: "Повторить" }).click();
expect(refetch).toHaveBeenCalledOnce(); expect(refetch).toHaveBeenCalledOnce();
}); });
it("shows a structural busy state before events are available", () => {
query.mockReturnValue({
data: undefined,
isError: false,
isLoading: true,
refetch: vi.fn(),
} as never);
renderPage();
const status = screen.getByRole("status", { name: "Загрузка" });
expect(status).toHaveAttribute("aria-busy", "true");
expect(status.querySelector("button")).toBeNull();
});
}); });
@@ -1,4 +1,12 @@
import { Button, Card, Group, Stack, Text, Title } from "@mantine/core"; import {
Button,
Card,
Group,
Skeleton,
Stack,
Text,
Title,
} from "@mantine/core";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useParams } from "react-router"; import { useParams } from "react-router";
@@ -7,7 +15,7 @@ import {
useBrokerageEvents, useBrokerageEvents,
} from "@/entities/brokerage-event"; } from "@/entities/brokerage-event";
import { formatMoney } from "@/entities/portfolio"; import { formatMoney } from "@/entities/portfolio";
import { StateView } from "@/shared/ui"; import { LoadingSkeleton, StateView } from "@/shared/ui";
type AccountEventsPageErrorProps = { type AccountEventsPageErrorProps = {
retry: () => void; retry: () => void;
@@ -36,11 +44,13 @@ const AccountEventsPageLoading: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<StateView <LoadingSkeleton label={t("states.loadingTitle")}>
loading <Skeleton height={32} width="40%" />
title={t("states.loadingTitle")} <Skeleton height={18} width="70%" />
text={t("states.loadingText")} {[0, 1, 2, 3].map((index) => (
/> <Skeleton key={index} height={82} radius="md" />
))}
</LoadingSkeleton>
); );
}; };
@@ -1,16 +1,29 @@
import { Group, Skeleton, Stack } from "@mantine/core";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { StateView } from "@/shared/ui"; import { LoadingSkeleton } from "@/shared/ui";
const AccountOperationsPageLoading: FC = () => { const AccountOperationsPageLoading: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<StateView <LoadingSkeleton label={t("states.loadingTitle")}>
loading <Skeleton height={32} width="40%" />
title={t("states.loadingTitle")} <Group grow>
text={t("states.loadingText")} <Skeleton height={48} radius="sm" />
/> <Skeleton height={48} radius="sm" />
</Group>
<Skeleton height={48} radius="sm" />
<Group>
<Skeleton height={36} width={110} radius="sm" />
<Skeleton height={36} width={110} radius="sm" />
</Group>
<Stack gap="xs">
{[0, 1, 2, 3].map((index) => (
<Skeleton key={index} height={64} radius="md" />
))}
</Stack>
</LoadingSkeleton>
); );
}; };
+9 -7
View File
@@ -1,11 +1,11 @@
import { Accordion, Alert, Button, Stack, Text } from "@mantine/core"; import { Accordion, Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import type { BrokerageAccount } from "@/entities/brokerage-account"; import type { BrokerageAccount } from "@/entities/brokerage-account";
import type { Portfolio } from "@/entities/portfolio"; import type { Portfolio } from "@/entities/portfolio";
import { formatSnapshotTime } from "@/entities/portfolio"; import { formatSnapshotTime } from "@/entities/portfolio";
import { StateView } from "@/shared/ui"; import { LoadingSkeleton, StateView } from "@/shared/ui";
import classes from "./AccountPage.module.css"; import classes from "./AccountPage.module.css";
import type { import type {
AccountPagePositionSection, AccountPagePositionSection,
@@ -51,11 +51,13 @@ const AccountPageLoading: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<StateView <LoadingSkeleton label={t("states.loadingTitle")}>
loading <Skeleton height={32} width="35%" />
title={t("states.loadingTitle")} <Skeleton height={120} radius="md" />
text={t("states.loadingText")} {[0, 1, 2].map((index) => (
/> <Skeleton key={index} height={52} radius="sm" />
))}
</LoadingSkeleton>
); );
}; };
@@ -1,9 +1,10 @@
import { Alert, Button, Paper, Stack, Text } from "@mantine/core"; import { Alert, Button, Paper, Skeleton, Stack, Text } from "@mantine/core";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import type { BrokerageEvent } from "@/entities/brokerage-event"; import type { BrokerageEvent } from "@/entities/brokerage-event";
import { formatMoney } from "@/entities/portfolio"; import { formatMoney } from "@/entities/portfolio";
import { LoadingSkeleton } from "@/shared/ui";
import classes from "../AccountPage.module.css"; import classes from "../AccountPage.module.css";
import type { AccountPageRecentEvents } from "../AccountPage.vm"; import type { AccountPageRecentEvents } from "../AccountPage.vm";
@@ -22,7 +23,11 @@ const RecentEvents: FC<RecentEventsProps> = (props) => {
return ( return (
<Stack gap="sm"> <Stack gap="sm">
{events.state === "loading" ? ( {events.state === "loading" ? (
<Text c="dimmed">{t("events.recentLoading")}</Text> <LoadingSkeleton label={t("events.recentLoading")}>
{[0, 1, 2].map((index) => (
<Skeleton key={index} height={48} radius="sm" />
))}
</LoadingSkeleton>
) : null} ) : null}
{events.state === "error" ? ( {events.state === "error" ? (
<Alert color="red">{t("events.recentError")}</Alert> <Alert color="red">{t("events.recentError")}</Alert>
@@ -1,8 +1,9 @@
import { Alert, Button, Stack, Text } from "@mantine/core"; import { Alert, Button, Skeleton, Stack, Text } from "@mantine/core";
import type { FC } from "react"; import type { FC } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import { LedgerEntryRow } from "@/entities/broker-operation"; import { LedgerEntryRow } from "@/entities/broker-operation";
import { LoadingSkeleton } from "@/shared/ui";
import type { AccountPageRecentOperations } from "../AccountPage.vm"; import type { AccountPageRecentOperations } from "../AccountPage.vm";
type RecentOperationsProps = { type RecentOperationsProps = {
@@ -16,7 +17,11 @@ const RecentOperations: FC<RecentOperationsProps> = (props) => {
return ( return (
<Stack gap="sm"> <Stack gap="sm">
{operations.state === "loading" ? ( {operations.state === "loading" ? (
<Text c="dimmed">{t("ledger.recentLoading")}</Text> <LoadingSkeleton label={t("ledger.recentLoading")}>
{[0, 1, 2].map((index) => (
<Skeleton key={index} height={48} radius="sm" />
))}
</LoadingSkeleton>
) : null} ) : null}
{operations.state === "error" ? ( {operations.state === "error" ? (
<Alert color="red">{t("ledger.recentError")}</Alert> <Alert color="red">{t("ledger.recentError")}</Alert>
+8 -6
View File
@@ -3,6 +3,7 @@ import {
Button, Button,
Group, Group,
Loader, Loader,
Skeleton,
Stack, Stack,
Text, Text,
Title, Title,
@@ -12,7 +13,7 @@ import { useTranslation } from "react-i18next";
import { Link } from "react-router"; import { Link } from "react-router";
import type { BrokerageAccountCard } from "@/entities/brokerage-account"; import type { BrokerageAccountCard } from "@/entities/brokerage-account";
import { BrokerageAccountList } from "@/entities/brokerage-account"; import { BrokerageAccountList } from "@/entities/brokerage-account";
import { StateView } from "@/shared/ui"; import { LoadingSkeleton, StateView } from "@/shared/ui";
type AccountsPageErrorProps = { type AccountsPageErrorProps = {
code?: string; code?: string;
@@ -42,11 +43,12 @@ const AccountsPageLoading: FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<StateView <LoadingSkeleton label={t("states.loadingTitle")}>
loading <Skeleton height={32} width="30%" />
title={t("states.loadingTitle")} {[0, 1, 2].map((index) => (
text={t("states.loadingText")} <Skeleton key={index} height={116} radius="md" />
/> ))}
</LoadingSkeleton>
); );
}; };
+18
View File
@@ -0,0 +1,18 @@
import { Stack } from "@mantine/core";
import type { FC, PropsWithChildren } from "react";
type LoadingSkeletonProps = PropsWithChildren<{
label: string;
}>;
const LoadingSkeleton: FC<LoadingSkeletonProps> = (props) => {
const { children, label } = props;
return (
<Stack aria-busy="true" aria-label={label} gap="md" role="status">
{children}
</Stack>
);
};
export { LoadingSkeleton };
+9 -5
View File
@@ -1,21 +1,25 @@
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { cleanup, render, screen } from "@testing-library/react"; import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest"; import { afterEach, describe, expect, it } from "vitest";
import { LoadingSkeleton } from "./LoadingSkeleton";
import { StateView } from "./StateView"; import { StateView } from "./StateView";
describe("StateView", () => { describe("StateView", () => {
afterEach(cleanup); afterEach(cleanup);
it("renders an accessible loading state with a loader", () => { it("renders an accessible structural loading region", () => {
render( render(
<MantineProvider> <MantineProvider>
<StateView loading text="Пожалуйста, подождите." title="Загрузка" /> <LoadingSkeleton label="Загрузка">
<div />
</LoadingSkeleton>
</MantineProvider>, </MantineProvider>,
); );
const status = screen.getByRole("status"); expect(screen.getByRole("status", { name: "Загрузка" })).toHaveAttribute(
expect(status).toHaveTextContent("Загрузка"); "aria-busy",
expect(screen.getByLabelText("Загрузка")).toBeInTheDocument(); "true",
);
}); });
it("renders an accessible error state", () => { it("renders an accessible error state", () => {
+3 -5
View File
@@ -1,22 +1,20 @@
import { Button, Loader, Paper, Stack, Text, Title } from "@mantine/core"; import { Button, Paper, Stack, Text, Title } from "@mantine/core";
import type { FC, ReactNode } from "react"; import type { FC, ReactNode } from "react";
type StateViewProps = { type StateViewProps = {
title: string; title: string;
text: string; text: string;
action?: ReactNode; action?: ReactNode;
loading?: boolean;
error?: boolean; error?: boolean;
}; };
const StateView: FC<StateViewProps> = (props) => { const StateView: FC<StateViewProps> = (props) => {
const { title, text, action, loading = false, error = false } = props; const { title, text, action, error = false } = props;
const role = loading ? "status" : error ? "alert" : undefined; const role = error ? "alert" : undefined;
return ( return (
<Paper p="xl" radius="md" shadow="xs" withBorder role={role}> <Paper p="xl" radius="md" shadow="xs" withBorder role={role}>
<Stack align="flex-start" gap="sm"> <Stack align="flex-start" gap="sm">
{loading ? <Loader aria-label={title} size="sm" /> : null}
<Title order={2}>{title}</Title> <Title order={2}>{title}</Title>
<Text c="dimmed">{text}</Text> <Text c="dimmed">{text}</Text>
{action} {action}
+1
View File
@@ -1,2 +1,3 @@
export { AppShell } from "./AppShell"; export { AppShell } from "./AppShell";
export { LoadingSkeleton } from "./LoadingSkeleton";
export { Button, StateView } from "./StateView"; export { Button, StateView } from "./StateView";