merge: 优化手机端录题切换、退出确认、分页跳页与页头布局

Refs: https://github.com/margrop/wrong-notebook/issues/105
This commit is contained in:
margrop
2026-12-04 18:41:56 +08:00
10 changed files with 116 additions and 17 deletions

View File

@@ -91,6 +91,7 @@ test.describe('Authentication Flow', () => {
await expect(userSettings).toBeVisible({ timeout: 5000 });
await userSettings.getByRole('tab', { name: /^(Account|账户)$/ }).click();
await userSettings.getByRole('button', { name: /^(Logout|退出登录)$/ }).click();
await acceptConfirmDialog(page);
await page.waitForURL('**/login');
// --- Login as Admin ---
@@ -134,6 +135,7 @@ test.describe('Authentication Flow', () => {
const adminSettings = page.getByRole('dialog');
await adminSettings.getByRole('tab', { name: /^(Account|账户)$/ }).click();
await adminSettings.getByRole('button', { name: /^(Logout|退出登录)$/ }).click();
await acceptConfirmDialog(page);
await page.waitForURL('**/login');
});

View File

@@ -72,6 +72,17 @@ test('错题列表跳页、位置恢复与常用筛选视图', async ({ page, sc
// 移动端高级筛选收进抽屉
await page.setViewportSize({ width: 390, height: 844 });
// 手机端分页器仍可跳页,翻页按钮放大后保持可点;先清除上一步留下的筛选
await page.getByRole('button', { name: '清除筛选' }).click();
await expect(page.getByText(`共 ${ITEM_COUNT} 道错题`).last()).toBeVisible({ timeout: 15000 });
const mobileJump = page.locator('input[type="number"]').first();
await expect(mobileJump).toBeVisible();
await mobileJump.fill('2');
await page.getByRole('button', { name: '跳转' }).click();
await expect(page.getByText(`显示第 19-36 条,共 ${ITEM_COUNT} 条`)).toBeVisible();
await expect(page.getByText(`${marker} 题目 18`)).toBeVisible();
await expect(page.getByText('2 / 6')).toBeVisible();
await page.getByRole('button', { name: '筛选条件' }).click();
const mobileSheet = page.getByRole('dialog');
await expect(mobileSheet.getByRole('heading', { name: '筛选条件' })).toBeVisible();

View File

@@ -0,0 +1,43 @@
import { test, expect } from './support/fixtures';
/** 手机窄屏基础控件:录题方式文案完整、页头返回与标题同行 */
test.describe('手机端基础控件', () => {
test.use({ viewport: { width: 375, height: 667 } });
test('[E2E-M10] 首页 4 个录题方式在 375px 下文案不截断', async ({ page, scenario }) => {
test.setTimeout(90000);
await scenario.login(page);
await page.goto('/');
const tabs = page.getByRole('tab');
await expect(tabs).toHaveCount(4);
for (const tab of await tabs.all()) {
const box = await tab.boundingBox();
expect(box).not.toBeNull();
expect(box!.x).toBeGreaterThanOrEqual(0);
expect(box!.x + box!.width).toBeLessThanOrEqual(375);
const label = tab.locator('span').last();
expect(await label.evaluate((element) => element.scrollWidth <= element.clientWidth + 1)).toBe(true);
}
await expect(page.getByRole('tab', { name: '拍照上传' })).toBeVisible();
await expect(page.getByRole('tab', { name: '导入题库文件' })).toBeVisible();
});
test('[E2E-M11] 子页面页头在手机端返回按钮与标题同行', async ({ page, scenario }) => {
test.setTimeout(90000);
await scenario.login(page);
await page.goto(`/notebooks/${scenario.book.id}`);
const heading = page.getByRole('heading', { name: scenario.book.name });
const back = page.getByRole('button', { name: '返回', exact: true });
await expect(heading).toBeVisible({ timeout: 15000 });
await expect(back).toBeVisible();
const headingBox = await heading.boundingBox();
const backBox = await back.boundingBox();
expect(headingBox).not.toBeNull();
expect(backBox).not.toBeNull();
// 两者处于同一行:中心高度接近,返回按钮在标题左侧
expect(Math.abs((headingBox!.y + headingBox!.height / 2) - (backBox!.y + backBox!.height / 2))).toBeLessThan(20);
expect(headingBox!.x).toBeGreaterThan(backBox!.x + backBox!.width - 1);
});
});

View File

@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({
signOut: vi.fn(),
shareCurrentPage: vi.fn().mockResolvedValue("clipboard"),
apiGet: vi.fn().mockResolvedValue({ aiProvider: "minimax" }),
confirmDialog: vi.fn(),
}));
vi.mock("next/navigation", () => ({
@@ -24,7 +25,7 @@ vi.mock("next-auth/react", () => ({
vi.mock("@/lib/share-page", () => ({ shareCurrentPage: mocks.shareCurrentPage }));
vi.mock("@/lib/api-client", () => ({ apiClient: { get: mocks.apiGet, post: vi.fn(), patch: vi.fn(), delete: vi.fn() } }));
vi.mock("@/lib/frontend-logger", () => ({ frontendLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn() } }));
vi.mock("@/lib/feedback", () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() }, confirmDialog: vi.fn() }));
vi.mock("@/lib/feedback", () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() }, confirmDialog: mocks.confirmDialog }));
vi.mock("@/lib/hooks/use-eula-gate", () => ({ useEulaGate: () => ({ pending: false, status: null, accept: vi.fn() }) }));
vi.mock("@/lib/hooks/use-page-telemetry", () => ({ usePageTelemetry: vi.fn() }));
vi.mock("@/lib/hooks/use-setup-redirect", () => ({ useSetupRedirect: vi.fn() }));
@@ -42,6 +43,7 @@ vi.mock("@/components/settings/question-type-settings", () => ({ QuestionTypeSet
import { AppShell } from "@/components/app-shell";
import { AccountLogoutSetting } from "@/components/settings/account-logout-setting";
import { LanguageProvider } from "@/contexts/LanguageContext";
import { translations } from "@/lib/translations";
let container: HTMLDivElement;
let root: Root;
@@ -49,11 +51,20 @@ const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard"
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
mocks.confirmDialog.mockResolvedValue(true);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
async function flush() {
const { promise, resolve } = Promise.withResolvers<void>();
await act(async () => {
setTimeout(resolve, 0);
await promise;
});
}
afterEach(async () => {
await act(async () => root.unmount());
container.remove();
@@ -214,10 +225,12 @@ describe("AppShell 顶栏与设置退出入口", () => {
await act(async () => {
logoutButton!.click();
});
await flush();
expect(mocks.confirmDialog).toHaveBeenCalledWith(translations.zh.app.logoutConfirm, { destructive: true });
expect(mocks.signOut).toHaveBeenCalledWith({ callbackUrl: "/login" });
});
it("AccountLogoutSetting 点击退出按钮触发 signOut", async () => {
it("AccountLogoutSetting 点击退出按钮先确认再触发 signOut", async () => {
await act(async () => {
root.render(
<LanguageProvider>
@@ -228,6 +241,25 @@ describe("AppShell 顶栏与设置退出入口", () => {
const button = container.querySelector("button")!;
await act(async () => button.click());
await flush();
expect(mocks.confirmDialog).toHaveBeenCalledWith(translations.zh.app.logoutConfirm, { destructive: true });
expect(mocks.signOut).toHaveBeenCalledWith({ callbackUrl: "/login" });
});
it("AccountLogoutSetting 取消确认时不退出", async () => {
mocks.confirmDialog.mockResolvedValueOnce(false);
await act(async () => {
root.render(
<LanguageProvider>
<AccountLogoutSetting />
</LanguageProvider>,
);
});
const button = container.querySelector("button")!;
await act(async () => button.click());
await flush();
expect(mocks.confirmDialog).toHaveBeenCalledTimes(1);
expect(mocks.signOut).not.toHaveBeenCalled();
});
});

View File

@@ -4,11 +4,17 @@ import { signOut } from "next-auth/react";
import { LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useLanguage } from "@/contexts/LanguageContext";
import { confirmDialog } from "@/lib/feedback";
/** 账户设置中的退出登录入口 */
export function AccountLogoutSetting() {
const { t } = useLanguage();
const handleLogout = async () => {
if (!(await confirmDialog(t.app.logoutConfirm, { destructive: true }))) return;
await signOut({ callbackUrl: "/login" });
};
return (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border p-4">
<div className="space-y-0.5">
@@ -25,7 +31,7 @@ export function AccountLogoutSetting() {
variant="outline"
size="sm"
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
onClick={() => signOut({ callbackUrl: "/login" })}
onClick={() => void handleLogout()}
>
<LogOut className="h-4 w-4" />
{t.app.logout}

View File

@@ -16,7 +16,7 @@ interface PageHeaderProps {
/** 统一的页面标题区:返回按钮 + 标题/副标题 + 右侧操作 */
export function PageHeader({ title, description, backHref, actions, titleAddon, className }: PageHeaderProps) {
return (
<div className={cn("flex flex-col gap-3 sm:flex-row sm:items-start", className)}>
<div className={cn("flex flex-wrap items-center gap-2 sm:flex-row sm:items-start sm:gap-3", className)}>
{backHref && <BackButton fallbackUrl={backHref} className="-ml-2 shrink-0" />}
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-1">

View File

@@ -83,12 +83,12 @@ export function Pagination({
.replace("{total}", total.toString())}
</div>
)}
<div className="flex items-center gap-1 order-1 sm:order-2">
<div className="flex flex-wrap items-center justify-center gap-1 order-1 sm:order-2">
{/* 首页 */}
<Button
variant="outline"
size="icon"
className="h-8 w-8"
className="h-9 w-9 sm:h-8 sm:w-8"
onClick={() => onPageChange(1)}
disabled={!canGoPrev}
title={t.pagination?.first || "First page"}
@@ -100,7 +100,7 @@ export function Pagination({
<Button
variant="outline"
size="icon"
className="h-8 w-8"
className="h-9 w-9 sm:h-8 sm:w-8"
onClick={() => onPageChange(page - 1)}
disabled={!canGoPrev}
title={t.pagination?.prev || "Previous page"}
@@ -134,23 +134,24 @@ export function Pagination({
{page} / {totalPages}
</span>
{/* 页码多时提供直接跳页,避免反复点下一页 */}
{/* 页码多时提供直接跳页,手机与桌面均可见 */}
{totalPages > MAX_VISIBLE_PAGES && (
<div className="hidden sm:flex items-center gap-1 ml-1">
<div className="flex items-center gap-1 ml-1">
<span className="text-xs text-muted-foreground">{t.pagination.jumpTo}</span>
<Input
type="number"
inputMode="numeric"
min={1}
max={totalPages}
value={jumpValue}
aria-label={t.pagination.jumpTo}
className="h-8 w-16 px-2 text-center"
className="h-9 w-16 px-2 text-center sm:h-8"
onChange={(event) => setJumpValue(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") jumpToPage();
}}
/>
<Button variant="outline" size="sm" className="h-8 px-2" onClick={jumpToPage}>
<Button variant="outline" size="sm" className="h-9 px-2 sm:h-8" onClick={jumpToPage}>
{t.pagination.jumpGo}
</Button>
</div>
@@ -160,7 +161,7 @@ export function Pagination({
<Button
variant="outline"
size="icon"
className="h-8 w-8"
className="h-9 w-9 sm:h-8 sm:w-8"
onClick={() => onPageChange(page + 1)}
disabled={!canGoNext}
title={t.pagination?.next || "Next page"}
@@ -172,7 +173,7 @@ export function Pagination({
<Button
variant="outline"
size="icon"
className="h-8 w-8"
className="h-9 w-9 sm:h-8 sm:w-8"
onClick={() => onPageChange(totalPages)}
disabled={!canGoNext}
title={t.pagination?.last || "Last page"}

View File

@@ -14,12 +14,13 @@ interface SegmentedControlProps<T extends string> {
className?: string;
}
/** 分段切换控件:等宽排列的选项,选中项浮起高亮 */
/** 分段切换控件:等宽排列的选项,选中项浮起高亮;4 项及以上在手机端折为 2×2 */
export function SegmentedControl<T extends string>({ options, value, onChange, className }: SegmentedControlProps<T>) {
const stacked = options.length >= 4;
return (
<div
className={cn("grid gap-1 rounded-xl bg-muted p-1", className)}
style={{ gridTemplateColumns: `repeat(${options.length}, minmax(0, 1fr))` }}
className={cn("grid gap-1 rounded-xl bg-muted p-1", stacked && "grid-cols-2 sm:grid-cols-4", className)}
style={stacked ? undefined : { gridTemplateColumns: `repeat(${options.length}, minmax(0, 1fr))` }}
role="tablist"
>
{options.map(({ value: optionValue, label, icon: Icon }) => {
@@ -32,12 +33,13 @@ export function SegmentedControl<T extends string>({ options, value, onChange, c
aria-selected={active}
className={cn(
"flex items-center justify-center gap-1.5 rounded-lg px-2 py-2.5 text-sm font-medium transition-all",
stacked && "flex-col gap-1 px-1 py-2 sm:flex-row sm:gap-1.5 sm:px-2 sm:py-2.5",
active ? "bg-card text-primary shadow-sm" : "text-muted-foreground hover:text-foreground"
)}
onClick={() => onChange(optionValue)}
>
{Icon && <Icon className="h-4 w-4 shrink-0" />}
<span className="truncate">{label}</span>
<span className={cn("truncate", stacked && "w-full text-center text-xs sm:text-sm")}>{label}</span>
</button>
);
})}

View File

@@ -201,6 +201,7 @@ export const en = {
tags: "Tags",
stats: "Stats",
logout: "Logout",
logoutConfirm: "Sign out now? Unsaved drafts will be lost.",
share: "Share",
shareCopied: "Link copied to clipboard",
shareCopyManual: "Copy the link below to share:",

View File

@@ -201,6 +201,7 @@ export const zh = {
tags: "标签管理",
stats: "统计中心",
logout: "退出登录",
logoutConfirm: "确定退出登录吗?未保存的草稿将丢失。",
share: "分享",
shareCopied: "链接已复制到剪贴板",
shareCopyManual: "请复制以下链接分享:",