Skip to content

feat: add recommendPage to onChange when pageSize changes#708

Merged
zombieJ merged 5 commits into
react-component:masterfrom
EmilyyyLiu:feat/recommend-page-on-size-change
Jul 3, 2026
Merged

feat: add recommendPage to onChange when pageSize changes#708
zombieJ merged 5 commits into
react-component:masterfrom
EmilyyyLiu:feat/recommend-page-on-size-change

Conversation

@EmilyyyLiu

@EmilyyyLiu EmilyyyLiu commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

需求背景

当用户切换 pageSize 时,当前页码有时会被重置为 1,用户体验不佳。特别是当用户浏览到很后面的页码,想增加每页显示数量时,需要重新回到前面查找之前看的数据。

相关 issue: ant-design/ant-design#30610

解决方案

onChange 增加第三个参数 recommendPage,只在切换 pageSize 时传递,用于计算保持用户当前数据位置的页码。

  • 普通翻页:onChange(page, pageSize)
  • 切换 pageSize:onChange(current, newSize, recommendPage)

使用方可以选择是否采纳推荐页码,完全向后兼容。

更新日志

语言 更新描述
🇺🇸 英文 🆕 Add recommendPage parameter to onChange callback when pageSize changes
🇨🇳 中文 🆕 为 onChange 增加 recommendPage 参数,切换 pageSize 时提供推荐页码

Summary by CodeRabbit

  • 新功能
    • 页大小变更时,onChange 回调新增第三个参数 info,可选包含 recommendPage 推荐页码,便于外部同步更合适的位置。
  • Bug 修复
    • 优化“保留大致位置”的推荐页计算与回退逻辑,提升分页切换后的稳定性,减少不符合预期的跳转。
  • 文档更新
    • README 与 README.zh-CN 补充并说明 onChange(page, pageSize, info?)info.recommendPage 的提供时机。
  • 测试
    • 更新并新增断言,覆盖新的回调入参结构与推荐页码差异场景。

- Add third parameter recommendPage to onChange callback
- calculatePage logic to preserve user's data position when changing pageSize
- Related issue: ant-design/ant-design#30610

Co-Authored-By: Claude <noreply@anthropic.com>
@vercel

vercel Bot commented Jun 29, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the afc163's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

分页尺寸变更时新增了推荐页码信息,并通过 onChange 第三个参数传出;接口导出、示例、文档和测试断言也同步更新。

Changes

onChange 新增 recommendPage 参数

Layer / File(s) Summary
接口签名与 changePageSize 计算逻辑
src/interface.ts, src/Pagination.tsx
PaginationOnChangeInfo 新增 recommendPagePaginationProps.onChange 扩展为接收第三参数 infochangePageSize 计算并传出 { recommendPage }
示例与断言更新
src/index.ts, docs/examples/jumper.tsx, tests/index.test.tsx, tests/simple.test.tsx, tests/sizer.test.tsx, README.md, README.zh-CN.md
类型重导出补充 PaginationOnChangeInfo;示例打印 info?.recommendPage;测试断言改为三参数调用;中英文 README 更新 onChange 签名与 recommendPage 说明。

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Pagination
  participant InternalState
  participant onChange回调
  Pagination->>Pagination: 计算 preservedPage / newCurrent / recommendPage
  Pagination->>InternalState: 更新 pageSize 与 current
  Pagination->>onChange回调: onChange(nextCurrent, size, { recommendPage })
Loading

Suggested reviewers: zombieJ, MadCcc

Poem

🐰 页大小一变,兔耳朵一抖,
推荐页码跳出来,轻轻点个头。
三个参数一起跑,回调不迷路,
翻页更顺手,咕叽咕叽走!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确概括了核心改动:在 pageSize 变化时为 onChange 增加 recommendPage 信息。
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new recommendPage parameter to the onChange callback in the Pagination component, designed to help preserve the user's data position when the page size changes. The changes include updates to the component implementation, TypeScript interfaces, documentation, and test cases. The reviewer identified an issue with the recommended page calculation, noting that using Math.ceil can cause users to skip data when reducing the page size. They suggested a more precise formula using Math.floor to target the start of the previous page range, along with corresponding updates to the test assertions.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/Pagination.tsx Outdated
Comment thread tests/simple.test.tsx Outdated
Comment thread tests/sizer.test.tsx Outdated
@EmilyyyLiu EmilyyyLiu closed this Jun 29, 2026
@EmilyyyLiu EmilyyyLiu reopened this Jun 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
tests/sizer.test.tsx (1)

53-70: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

补一个 recommendPage !== current 的回归用例。

当前断言只覆盖第一页,无法防止保留位置公式回退。建议增加一个后续页场景,例如 defaultCurrent={6}20 -> 50 时应回调 (6, 50, 3)

建议补充测试
   it('should onChange called when pageSize change', () => {
     const onChange = jest.fn();
     const { container, getByRole } = render(
       <Pagination
         sizeChangerRender={sizeChangerRender}
         onChange={onChange}
         total={500}
         defaultPageSize={20}
       />,
     );
     fireEvent.mouseDown(getByRole('combobox'));
     expect(container.querySelectorAll('.rc-select-item')[2]).toHaveTextContent(
       '50 条/页',
     );
     const pageSize1 = container.querySelectorAll('.rc-select-item')[0];
     fireEvent.click(pageSize1);
     expect(onChange).toHaveBeenCalled();
     expect(onChange).toHaveBeenLastCalledWith(1, 10, 1);
   });
+
+  it('should recommend preserved page when pageSize changes from later page', () => {
+    const onChange = jest.fn();
+    const { container, getByRole } = render(
+      <Pagination
+        sizeChangerRender={sizeChangerRender}
+        onChange={onChange}
+        total={500}
+        defaultCurrent={6}
+        defaultPageSize={20}
+      />,
+    );
+
+    fireEvent.mouseDown(getByRole('combobox'));
+    const pageSize50 = container.querySelectorAll('.rc-select-item')[2];
+    fireEvent.click(pageSize50);
+
+    expect(onChange).toHaveBeenLastCalledWith(6, 50, 3);
+  });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/sizer.test.tsx` around lines 53 - 70, Add a regression test in the
Pagination sizing spec to cover the recommendPage !== current case, since the
current assertion only checks page 1 and won’t catch a preserved-position
regression. Update the test around the existing Pagination/onChange flow in
sizer.test.tsx to use a later page scenario such as defaultCurrent={6} with a
page-size change from 20 to 50, and assert that the Pagination callback receives
the recomputed page value (for example, (6, 50, 3)) instead of always snapping
to 1.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tests/sizer.test.tsx`:
- Around line 53-70: Add a regression test in the Pagination sizing spec to
cover the recommendPage !== current case, since the current assertion only
checks page 1 and won’t catch a preserved-position regression. Update the test
around the existing Pagination/onChange flow in sizer.test.tsx to use a later
page scenario such as defaultCurrent={6} with a page-size change from 20 to 50,
and assert that the Pagination callback receives the recomputed page value (for
example, (6, 50, 3)) instead of always snapping to 1.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9bd13a2c-d84d-4cbc-b3cd-7650d3fd5bce

📥 Commits

Reviewing files that changed from the base of the PR and between a7784f5 and edab4c8.

📒 Files selected for processing (3)
  • src/Pagination.tsx
  • tests/simple.test.tsx
  • tests/sizer.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/simple.test.tsx

@codecov

codecov Bot commented Jun 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.69%. Comparing base (828a20e) to head (b8cc552).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #708   +/-   ##
=======================================
  Coverage   99.69%   99.69%           
=======================================
  Files           4        4           
  Lines         329      331    +2     
  Branches      151      152    +1     
=======================================
+ Hits          328      330    +2     
  Misses          1        1           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread src/interface.ts Outdated
…ution

Co-Authored-By: Claude <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/interface.ts (1)

61-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

可选:将 info 对象类型提取为具名类型。

内联的 { recommendPage?: number } 类型目前仅在此处出现一次,若后续需要在外部(如消费者代码、文档)引用该类型,建议提取为具名接口并导出,便于复用和后续扩展字段。

♻️ 提取具名类型示例
+export interface PaginationOnChangeInfo {
+  recommendPage?: number;
+}
+
 export interface PaginationProps
   extends Partial<PaginationData>, React.AriaAttributes {
   onChange?: (
     page: number,
     pageSize: number,
-    info?: { recommendPage?: number },
+    info?: PaginationOnChangeInfo,
   ) => void;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/interface.ts` around lines 61 - 65, The inline info parameter type in
onChange is only used once and should be extracted into a named, exported type
for reuse and future extension. Update the interface in interface.ts by
introducing a dedicated type for the info object, give it a descriptive name
that reflects recommendPage, and reference that type from onChange so consumers
and docs can import it directly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/interface.ts`:
- Around line 61-65: The inline info parameter type in onChange is only used
once and should be extracted into a named, exported type for reuse and future
extension. Update the interface in interface.ts by introducing a dedicated type
for the info object, give it a descriptive name that reflects recommendPage, and
reference that type from onChange so consumers and docs can import it directly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 208f37a4-5af3-4aab-af18-d5035385054f

📥 Commits

Reviewing files that changed from the base of the PR and between ec587c1 and f9b453b.

📒 Files selected for processing (6)
  • docs/examples/jumper.tsx
  • src/Pagination.tsx
  • src/interface.ts
  • tests/index.test.tsx
  • tests/simple.test.tsx
  • tests/sizer.test.tsx
✅ Files skipped from review due to trivial changes (3)
  • tests/sizer.test.tsx
  • tests/simple.test.tsx
  • docs/examples/jumper.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/index.test.tsx
  • src/Pagination.tsx

@zombieJ

zombieJ commented Jul 3, 2026

Copy link
Copy Markdown
Member

来自 Code Review Skill

这个 PR 在做什么

这个 PR 给 PaginationonChange 增加可选第三参数 info.recommendPage,只在切换 pageSize 时传出,用来提示调用方如何保持原数据位置。实现没有直接把当前页改成推荐页,而是继续保持原有 nextCurrent 逻辑,因此运行时行为基本向后兼容。示例和部分测试断言也同步改成了三参数回调。

结论

有条件合并

核心实现方向没看到明显逻辑问题;Math.floor(((current - 1) * pageSize) / size) + 1 也更符合“保留旧页首条数据位置”的语义。建议合并前补齐公开 API 文档和关键回归测试。CI 里主测试、CodeQL、Codecov 都过了,只有 Vercel preview 是授权失败类状态。

问题清单

🔴 高优先级(阻塞合并)

无。

🟡 中优先级(建议修复)

  • 公开 API 文档仍是旧签名README.md:104README.zh-CN.md:104
    docs/index.md 直接 embed README,所以站点 API 表也会继续显示 onChange(page, pageSize)。这次新增的是公共回调契约,建议把中英文 README 都更新为包含 info?: { recommendPage?: number },并说明该字段仅在切换 pageSize 时传入。

  • 缺少 recommendPage !== current 的核心回归测试tests/sizer.test.tsx:53
    当前测试只覆盖第一页切换,recommendPage 永远是 1,即使公式退化也很难暴露。建议补一个后续页场景,例如 defaultCurrent={6}defaultPageSize={20}、切到 50,断言 onChange 收到 (6, 50, { recommendPage: 3 })

🟢 低优先级(可选改进)

  • 可考虑导出具名 info 类型src/interface.ts:61
    现在 { recommendPage?: number } 是内联类型。若后续 Ant Design 或用户代码需要复用这个第三参数类型,导出如 PaginationOnChangeInfo 会更方便;不是必须,但对公共 API 更友好。

@EmilyyyLiu EmilyyyLiu force-pushed the feat/recommend-page-on-size-change branch from 7632736 to b8cc552 Compare July 3, 2026 04:30

@zombieJ zombieJ left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@zombieJ zombieJ merged commit 367cb4d into react-component:master Jul 3, 2026
11 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants