Files
cc-switch/tests/components/TablePagination.test.tsx
T
mashiro 79ba7982aa feat(usage): restructure the usage page layout (#8711)
* feat(usage): restructure the usage page layout

- Header: one sync button that shows when it last synced, next to a settings
  button; the settings sheet now holds data sources, display and pricing.
- Scope bar: date first, app chips, and one cascading provider / model menu.
- Overview: a selectable metric strip drives the trend chart and heatmap; the
  four token parts fold into an expandable second row. Hit-rate axis starts
  near the lowest value; hourly labels are short; new terracotta chart color.
- Detail panel: tabs with counts; tables scroll sideways at natural column
  widths, pin the time / app columns, group columns with wider gaps, and
  animate rows that arrive on refresh.
- Request detail drawer: no per-row dividers, no duplicate session rows.
- Empty values show an em dash; dark-mode surfaces use one token per role.

* feat(usage): let people pick how many request logs fit on a page

The pagination bar gets a rows-per-page menu (10 / 20 / 50, default 20),
remembered on this device. It stays visible on a single page as long as
there are more rows than the smallest size, so a larger choice can still be
undone. Changing the size keeps the first visible row on screen, and the
rows it adds are not animated as newly arrived requests.

* fix(usage): polish details found in review

- New-row highlight keeps a pinned column's edge shadow instead of replacing it.
- Pinned cells only follow row hover on rows that can be clicked.
- Update a stale comment about the metric strip spacing.

* fix(usage): fix issues found in branch review

- Heatmap in hit-rate mode: a day with traffic but a 0% hit rate is now
  shaded instead of looking idle, and the tooltip shows the hit rate.
  The heatmap reuses the trend chart's hitRateOf instead of its own copy.
- Turkish: add the request log column labels and the columns menu title.
- Sync button: when auto scan is off, the tooltip says so.
- Columns menu: concurrent saves no longer drop later toggles; a failed
  save reverts only once the last save returns.
- Tab counts query only the open tab; other tabs show their cached count.
- UsageDashboard uses the shared useElementWidth instead of its own copy.
- Note the two-column limit of the pinned-column offset.

* fix(usage): keep heatmap tooltip rows on one line

The added hit-rate row made the label column wider, so the card near
the right edge wrapped values like "7640.5 万" and the label itself.

* fix(usage): shorten the auto-scan-off sync tooltip to one line

The longer sentence wrapped inside the pill-shaped tooltip and broke
mid-word.

* fix(usage): open pricing as a sub-page so its editor can be used

Pricing lived in a modal Dialog, but the add/edit pricing editor is a
FullScreenPanel portaled into #content-area. The dialog's overlay sat
above it and Radix set pointer-events: none on body while the dialog was
open, so the editor's fields and save button could not be used. Pricing
is now a FullScreenPanel too, the same pattern as other nested panels.

* fix(usage): show exact metric values in the app tooltip

The metric strip used native title attributes for the exact numbers.
Use HoverTip instead, anchored to the number and opening to the right,
so it does not cover the expanded token row. No tip while the cell
shows a placeholder.
2026-10-23 10:59:12 +08:00

125 lines
4.4 KiB
TypeScript

import { useState } from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import {
TablePagination,
useClientPagination,
} from "@/components/usage/TablePagination";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) =>
options && "total" in options ? `${key}:${options.total}` : key,
i18n: { resolvedLanguage: "en", language: "en" },
}),
}));
function Harness({ count }: { count: number }) {
const [filter, setFilter] = useState("a");
const rows = Array.from({ length: count }, (_, i) => `row-${i + 1}`);
const pagination = useClientPagination(rows, filter);
return (
<div>
<button type="button" onClick={() => setFilter("b")}>
change-filter
</button>
<ul>
{pagination.pageRows.map((row) => (
<li key={row}>{row}</li>
))}
</ul>
<TablePagination
page={pagination.page}
totalPages={pagination.totalPages}
total={pagination.total}
onPageChange={pagination.setPage}
/>
</div>
);
}
describe("useClientPagination + TablePagination", () => {
it("pages rows 20 at a time and resets when the filter changes", async () => {
const user = userEvent.setup();
render(<Harness count={45} />);
expect(screen.getByText("usage.totalRecords:45")).toBeInTheDocument();
expect(screen.getAllByRole("listitem")).toHaveLength(20);
expect(screen.getByText("/ 3")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "usage.prevPage" }),
).toBeDisabled();
await user.click(screen.getByRole("button", { name: "usage.nextPage" }));
expect(screen.getByText("row-21")).toBeInTheDocument();
// 输入页码跳到最后一页:只剩 5 行
const input = screen.getByRole("textbox", {
name: "usage.pageInputPlaceholder",
});
await user.clear(input);
await user.type(input, "3{Enter}");
expect(screen.getAllByRole("listitem")).toHaveLength(5);
expect(
screen.getByRole("button", { name: "usage.nextPage" }),
).toBeDisabled();
// 超出范围的页码不生效
await user.clear(input);
await user.type(input, "9{Enter}");
expect(screen.getByText("row-41")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "change-filter" }));
expect(screen.getByText("row-1")).toBeInTheDocument();
});
it("draws no pagination bar when everything fits on one page", () => {
render(<Harness count={3} />);
expect(screen.getAllByRole("listitem")).toHaveLength(3);
expect(
screen.queryByRole("button", { name: "usage.nextPage" }),
).not.toBeInTheDocument();
expect(screen.queryByText("usage.totalRecords:3")).not.toBeInTheDocument();
});
it("offers rows per page, even on a single page, once there are more rows than the smallest size", async () => {
Element.prototype.scrollIntoView = vi.fn();
const user = userEvent.setup();
const onPageSizeChange = vi.fn();
const props = {
page: 0,
onPageChange: vi.fn(),
pageSize: 50,
pageSizeOptions: [10, 20, 50],
onPageSizeChange,
};
const { rerender, container } = render(
<TablePagination {...props} totalPages={1} total={8} />,
);
// 比最小一档还少:没什么可调的
expect(container).toBeEmptyDOMElement();
// 只有一页,但调小以后会分页:要能找回这个下拉
rerender(<TablePagination {...props} totalPages={1} total={30} />);
await user.click(
screen.getByRole("combobox", { name: "usage.pageSizeLabel" }),
);
// 选项依次是 10 / 20 / 50(测试里的 t 只返回键名)
await user.click((await screen.findAllByRole("option"))[0]);
expect(onPageSizeChange).toHaveBeenCalledWith(10);
});
it("clamps to the last page when rows shrink", async () => {
const user = userEvent.setup();
const { rerender } = render(<Harness count={45} />);
await user.click(screen.getByRole("button", { name: "usage.nextPage" }));
await user.click(screen.getByRole("button", { name: "usage.nextPage" }));
expect(screen.getByText("row-41")).toBeInTheDocument();
rerender(<Harness count={25} />);
expect(screen.getByText("row-21")).toBeInTheDocument();
expect(screen.getByText("/ 2")).toBeInTheDocument();
});
});