Skip to content

feat: scrollTo add align support#1469

Open
EmilyyyLiu wants to merge 7 commits intoreact-component:masterfrom
EmilyyyLiu:liuh-scroll
Open

feat: scrollTo add align support#1469
EmilyyyLiu wants to merge 7 commits intoreact-component:masterfrom
EmilyyyLiu:liuh-scroll

Conversation

@EmilyyyLiu
Copy link
Copy Markdown

@EmilyyyLiu EmilyyyLiu commented Mar 31, 2026

Summary

为 Table 组件的 scrollTo 方法增加 align 参数支持,类似于虚拟列表中的对齐方式。

Feature

  • align: 'start' - 滚动到顶部
  • align: 'center' - 滚动到中间
  • align: 'end' - 滚动到底部
  • align: 'nearest' - 智能滚动(默认)

Related Issue

ant-design/ant-design#45945

Usage

tableRef.current?.scrollTo({
  index: 9,
  align: 'start', // 'center' | 'end' | 'nearest'
});

也可以结合 offset 使用:

tableRef.current?.scrollTo({
  index: 9,
  align: 'center',
  offset: 10,
});

Summary by CodeRabbit

发版说明

  • 新功能
    • Table 组件新增公开方法 scrollTo,支持 align(start/center/end/nearest)和 offset 等配置;虚拟滚动场景对 align 有约束(不支持 center),新增对应虚拟滚动配置类型。
  • 文档
    • README 增补 scrollTo 使用说明与参数示例,更新了 ScrollConfig 中 align/offset 的描述。
  • 示例
    • 增加示例按钮展示不同 align 与 offset 组合的滚动效果。
  • 测试
    • 补充了针对 align 行为及带 offset 的滚动计算的测试覆盖。

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 31, 2026

Someone is attempting to deploy a commit to the React Component Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 31, 2026

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0bb86f23-97b1-42fa-9823-d322a4ca5dc0

📥 Commits

Reviewing files that changed from the base of the PR and between c71b494 and ec47eb8.

📒 Files selected for processing (1)
  • src/VirtualTable/BodyGrid.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/VirtualTable/BodyGrid.tsx

Walkthrough

为 Table 组件的公开方法 scrollTo 新增可选参数 alignstart | center | end | nearest,默认 nearest),在文档、示例、类型、实现与测试中同步引入并在有无 offset 时分别调整原生滚动或计算目标 top 后调用容器滚动逻辑。

Changes

Cohort / File(s) Summary
文档
README.md
新增 Methods 节,记录 Table.scrollToalign 参数、允许值和默认行为。
示例
docs/examples/scrollY.tsx, docs/examples/virtual.tsx
为示例添加按钮,调用 tblRef.current?.scrollTo(...) 覆盖 align(start/center/end/nearest)及带 offset 的组合,用于交互演示。
类型定义
src/interface.ts
ScrollConfig 中新增可选 align?: ScrollLogicalPosition,新增导出类型 VirtualScrollConfig = ScrollConfig & { align?: Exclude<ScrollLogicalPosition, 'center'> },并更新 offset 注释以说明与 align 的组合语义。
核心实现
src/Table.tsx, src/VirtualTable/BodyGrid.tsx
Table.scrollTo 解构 align:无 offset 时调用 element.scrollIntoView({ block: align ?? 'nearest' });有 offset 时基于容器/元素度量与 align 计算目标 top 并调用 container.scrollTo({ top })。Virtual BodyGrid 的 GridRef.scrollTo 改为接受 VirtualScrollConfig,将 align 映射为虚拟列表的 top/bottom/auto 并始终传入 listRef.current?.scrollTo
测试
tests/refs.spec.tsx, tests/Virtual.spec.tsx
新增/调整测试覆盖 align 在无 offset 与有 offset 时的行为,验证虚拟表格中 align 的映射关系及与 offset 共存的参数传递与计算。

Sequence Diagram(s)

sequenceDiagram
    participant Button
    participant TableRef
    participant Container as ScrollContainer
    participant Element as TargetElement
    participant VirtualList

    Button->>TableRef: call scrollTo({ index/key/top, offset?, align? })
    TableRef->>Container: resolve scroll container & target element
    alt target is in DOM (non-virtual)
        alt no offset
            TableRef->>Element: Element.scrollIntoView({ block: align ?? 'nearest' })
        else offset provided
            TableRef->>Container: compute targetTop using element.offsetTop/offsetHeight, clientHeight, scrollTop and align
            TableRef->>Container: Container.scrollTo({ top: targetTop [+ offset] })
        end
    else virtual list
        TableRef->>VirtualList: map align -> virtualAlign (top/bottom/auto) and pass { index/key, offset?, align: virtualAlign }
        VirtualList->>VirtualList: perform virtual scrollTo with provided config
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 分钟

Possibly related PRs

Suggested reviewers

  • afc163
  • zombieJ

我是小兔轻轻跳,表格行间把路找,
start 把我顶上来,end 把我落下靠,
center 居中瞧一瞧,nearest 就近不骄傲,
offset 小助力,按下按钮行现身 🐰✨

🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题'feat: scrollTo add align support'准确清晰地概括了PR的主要变更,即为Table组件的scrollTo方法添加align参数支持。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 and usage tips.

Copy link
Copy Markdown
Contributor

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

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 the align parameter to the scrollTo method of the Table component, allowing users to specify vertical alignment (start, center, end, nearest) when scrolling to a specific row. The changes include updates to the ScrollConfig interface, implementation logic in src/Table.tsx to handle alignment both with and without offsets, new documentation in the README, and comprehensive unit tests. Review feedback suggests translating README descriptions to English for consistency, updating outdated comments in the interface definition, and refining the alignMap type for better type safety and behavioral consistency with the documentation.

EmilyyyLiu and others added 3 commits March 31, 2026 10:29
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/interface.ts (1)

39-47: ⚠️ Potential issue | 🟡 Minor

offset 的类型注释已经和新行为冲突了。

这里还写着“设置 offset 后总是顶对齐”,但本次改动已经允许 align 参与定位。这个类型是公开 API,IDE 悬浮提示会直接误导调用方;建议把说明改成“offset 会叠加到按 align 计算出的目标位置”,或者如果只打算保留顶对齐,就把运行时逻辑收回到同一约束。

✏️ 建议同步注释
   /**
    * Additional offset in pixels to apply to the scroll position.
    * Only effective when using `key` or `index` mode.
    * Ignored when using `top` mode.
-   * When offset is set, the target element will always be aligned to the top of the container.
+   * In `key` / `index` mode, `offset` is added to the position resolved by `align`.
    */
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/interface.ts` around lines 39 - 47, The JSDoc for the offset property is
out-of-date: update the comment for offset (the offset?: number; declaration) to
state that offset is added to the target position computed from align
(ScrollLogicalPosition) rather than forcing top alignment; mention that offset
is effective when using key/index modes and will be applied on top of the align
calculation (or alternatively revert runtime behavior to force top alignment if
you prefer keeping the old doc), and ensure the phrase "always aligned to the
top" is removed so IDE hover shows the correct public API behavior for offset
and align.
src/Table.tsx (1)

354-380: ⚠️ Potential issue | 🟠 Major

align: 'nearest' 在 offset 分支里实际上没有被支持。

Line 354 先把 align 默认成了 'nearest',Line 377 又把 'nearest' 直接映射成 elementTop。这样 scrollTo({ index, offset, align: 'nearest' }) 和旧的 scrollTo({ index, offset }) 完全等价,都会退化成顶对齐,而不是“最小滚动”。如果这里是想兼容老行为,建议保留 align 的原始 undefined 状态:未显式传入时继续走旧逻辑;显式传入 'nearest' 时再按当前 scrollTop / elementBottom 计算真正的 nearest。

💡 一种兼容旧行为的修正方式
-          const { index, top, key, offset, align = 'nearest' } = config;
+          const { index, top, key, offset, align } = config;

           if (validNumberValue(top)) {
             // In top mode, offset is ignored
             scrollBodyRef.current?.scrollTo({ top });
           } else {
             const mergedKey = key ?? getRowKey(mergedData[index]);
             const targetElement = scrollBodyRef.current.querySelector(
               `[data-row-key="${mergedKey}"]`,
             );
             if (targetElement) {
               if (!offset) {
-                targetElement.scrollIntoView({ block: align });
+                targetElement.scrollIntoView({ block: align ?? 'nearest' });
               } else {
                 const container = scrollBodyRef.current;
+                const currentTop = container.scrollTop;
                 const elementTop = (targetElement as HTMLElement).offsetTop;
                 const elementHeight = (targetElement as HTMLElement).offsetHeight;
+                const elementBottom = elementTop + elementHeight;
                 const containerHeight = container.clientHeight;
+                const containerBottom = currentTop + containerHeight;
+                const mergedAlign = align ?? 'start';

-                const alignMap: Record<string, number> = {
-                  start: elementTop,
-                  end: elementTop + elementHeight - containerHeight,
-                  center: elementTop + (elementHeight - containerHeight) / 2,
-                  nearest: elementTop,
-                };
-                const targetTop = alignMap[align] ?? elementTop;
+                let targetTop = elementTop;
+                switch (mergedAlign) {
+                  case 'end':
+                    targetTop = elementBottom - containerHeight;
+                    break;
+                  case 'center':
+                    targetTop = elementTop - (containerHeight - elementHeight) / 2;
+                    break;
+                  case 'nearest':
+                    if (elementTop < currentTop) {
+                      targetTop = elementTop;
+                    } else if (elementBottom > containerBottom) {
+                      targetTop = elementBottom - containerHeight;
+                    } else {
+                      targetTop = currentTop;
+                    }
+                    break;
+                  default:
+                    targetTop = elementTop;
+                }
                 container.scrollTo({ top: targetTop + offset });
               }
             }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Table.tsx` around lines 354 - 380, The current logic defaults align to
'nearest' and then treats 'nearest' as elementTop, which breaks true nearest
behavior and conflates explicit nearest with the old undefined case; change the
destructuring so align defaults to undefined (const { index, top, key, offset,
align } = config), preserve legacy behavior when align is undefined (keep
existing top-based calculation used by scrollTo({index, offset}) ), and
implement real "nearest" handling inside the offset branch: compute
container.scrollTop, elementTop and elementBottom, then choose the smallest
scroll delta (top, center, or end) to produce the nearest targetTop when align
=== 'nearest'; update the alignMap/selection in the code that uses
scrollBodyRef, mergedData, getRowKey and targetElement accordingly.
🧹 Nitpick comments (1)
tests/refs.spec.tsx (1)

114-186: 这组测试还区分不出 align 是否真的生效。

现在的 mock 只记录了 scrollIntoView 的目标元素,没有记录 { block } 参数;而且 JSDOM 下 offsetTopoffsetHeightclientHeight 默认都是 0,所以 startcenterendnearest 在这里基本会退化成同一种结果。实现就算把 align 忽略掉,这些用例大概率也还能通过。

🧪 可参考的补强方向
 let scrollParam: any = null;
 let scrollIntoViewElement: HTMLElement = null;
+let scrollIntoViewParam: ScrollIntoViewOptions | undefined;

   beforeAll(() => {
     spyElementPrototypes(HTMLElement, {
       scrollTo: (_: any, param: any) => {
         scrollParam = param;
       },
-      scrollIntoView() {
+      scrollIntoView(param?: ScrollIntoViewOptions) {
         // eslint-disable-next-line `@typescript-eslint/no-this-alias`
         scrollIntoViewElement = this;
+        scrollIntoViewParam = param;
       },
     });
   });

   beforeEach(() => {
     scrollParam = null;
     scrollIntoViewElement = null;
+    scrollIntoViewParam = undefined;
   });

   // Align start - should use scrollIntoView
   scrollIntoViewElement = null;
   ref.current.scrollTo({ index: 0, align: 'start' });
   expect(scrollIntoViewElement.textContent).toEqual('light');
+  expect(scrollIntoViewParam).toMatchObject({ block: 'start' });

align + offset 这组再给 row / container 手动补一组不同的几何值后,才能真正把 startcenterendnearest 的计算分开。

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/interface.ts`:
- Around line 39-47: The JSDoc for the offset property is out-of-date: update
the comment for offset (the offset?: number; declaration) to state that offset
is added to the target position computed from align (ScrollLogicalPosition)
rather than forcing top alignment; mention that offset is effective when using
key/index modes and will be applied on top of the align calculation (or
alternatively revert runtime behavior to force top alignment if you prefer
keeping the old doc), and ensure the phrase "always aligned to the top" is
removed so IDE hover shows the correct public API behavior for offset and align.

In `@src/Table.tsx`:
- Around line 354-380: The current logic defaults align to 'nearest' and then
treats 'nearest' as elementTop, which breaks true nearest behavior and conflates
explicit nearest with the old undefined case; change the destructuring so align
defaults to undefined (const { index, top, key, offset, align } = config),
preserve legacy behavior when align is undefined (keep existing top-based
calculation used by scrollTo({index, offset}) ), and implement real "nearest"
handling inside the offset branch: compute container.scrollTop, elementTop and
elementBottom, then choose the smallest scroll delta (top, center, or end) to
produce the nearest targetTop when align === 'nearest'; update the
alignMap/selection in the code that uses scrollBodyRef, mergedData, getRowKey
and targetElement accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ae9a085b-6c5c-49f6-88fe-5afb49c27bb0

📥 Commits

Reviewing files that changed from the base of the PR and between 45f97df and b4bc3f7.

⛔ Files ignored due to path filters (4)
  • tests/__snapshots__/ExpandRow.spec.jsx.snap is excluded by !**/*.snap
  • tests/__snapshots__/FixedColumn.spec.tsx.snap is excluded by !**/*.snap
  • tests/__snapshots__/Summary.spec.tsx.snap is excluded by !**/*.snap
  • tests/__snapshots__/Table.spec.jsx.snap is excluded by !**/*.snap
📒 Files selected for processing (5)
  • README.md
  • docs/examples/scrollY.tsx
  • src/Table.tsx
  • src/interface.ts
  • tests/refs.spec.tsx

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/interface.ts`:
- Around line 43-47: The public ScrollConfig.align option is being ignored in
the virtual path: update the virtual scroller code (the BodyGrid virtual branch
that handles offset/align in the scrollTo logic) to respect the
ScrollConfig.align value instead of forcibly setting align = 'top'; ensure the
scrollTo call (and any helper that computes target offset) reads the external
align and offset fields from ScrollConfig and computes the final scroll position
accordingly so scrollTo({ index, align: 'center', offset: 10 }) behaves as
documented. Reference symbols: ScrollConfig, align, offset, scrollTo, BodyGrid
(virtual branch).

In `@src/Table.tsx`:
- Around line 365-380: The current offset-branch mapping in Table.tsx maps align
'nearest' to elementTop causing unnecessary jumps; change the 'nearest' case in
the alignMap (or replace alignMap with conditional logic) to compute the minimal
scroll needed: read container.scrollTop and containerHeight, elementTop and
elementBottom (= elementTop + elementHeight), and if elementTop < scrollTop set
targetTop = elementTop, else if elementBottom > scrollTop + containerHeight set
targetTop = elementBottom - containerHeight, else set targetTop = scrollTop (no
change); then use container.scrollTo({ top: targetTop + offset }) so 'nearest'
only scrolls when the row is outside the viewport.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f7624530-43b1-4628-a4fc-e07079cf3fde

📥 Commits

Reviewing files that changed from the base of the PR and between b4bc3f7 and 1027f17.

📒 Files selected for processing (3)
  • README.md
  • src/Table.tsx
  • src/interface.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • README.md

- Add VirtualScrollConfig type with Exclude<ScrollLogicalPosition, 'center'>
- Implement align mapping for virtual table (start->top, end->bottom, nearest->auto)
- Add default align 'auto' when neither align nor offset provided
- Add backward compatibility: default to 'top' when offset provided but align not
- Update tests to cover align parameter scenarios
- Fix offset JSDoc comment

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/Virtual.spec.tsx (1)

427-450: 建议补充 align: 'center'(或非法值)契约测试

当前只覆盖了 start/end/nearest。建议再补一条 center(或非法 align)断言,明确是“降级为 auto”还是“直接拒绝”,避免后续回归到隐式行为。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/Virtual.spec.tsx` around lines 427 - 450, Add a test case calling
tblRef.current.scrollTo with align: 'center' (and another with an invalid align
like 'invalid') and assert how the implementation handles them by checking
global.scrollToConfig; specifically call scrollTo({ index: 50, align: 'center'
}) and expect global.scrollToConfig.align === 'auto' (and likewise for the
invalid value) so the behavior is explicit; place these assertions alongside the
existing scrollTo tests that reference scrollTo, Reference, getTable and
global.scrollToConfig and use await waitFakeTimer() before each expect.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/VirtualTable/BodyGrid.tsx`:
- Around line 90-97: alignMap[align] can be undefined if align holds an
unexpected value, so update the virtualAlign computation in BodyGrid (the
variables alignMap, virtualAlign, align, offset) to always produce a valid 'top'
| 'bottom' | 'auto' by using a safe fallback: use the mapped value only if
present (e.g., alignMap[align] !== undefined) otherwise fall back to offset ?
'top' : 'auto' (or default 'auto'), ensuring scrollTo always receives a valid
string.

---

Nitpick comments:
In `@tests/Virtual.spec.tsx`:
- Around line 427-450: Add a test case calling tblRef.current.scrollTo with
align: 'center' (and another with an invalid align like 'invalid') and assert
how the implementation handles them by checking global.scrollToConfig;
specifically call scrollTo({ index: 50, align: 'center' }) and expect
global.scrollToConfig.align === 'auto' (and likewise for the invalid value) so
the behavior is explicit; place these assertions alongside the existing scrollTo
tests that reference scrollTo, Reference, getTable and global.scrollToConfig and
use await waitFakeTimer() before each expect.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 81dac262-9019-4940-8d21-1af4a9856b5f

📥 Commits

Reviewing files that changed from the base of the PR and between 1027f17 and 833f5ce.

📒 Files selected for processing (3)
  • src/VirtualTable/BodyGrid.tsx
  • src/interface.ts
  • tests/Virtual.spec.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/interface.ts

- Fix nearest align to compute position after offset, then determine if scrolling is needed
- Add align test buttons to scrollY and virtual demo files
- Update center calculation formula

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
src/Table.tsx (1)

377-395: ⚠️ Potential issue | 🟠 Major

offset 分支的默认对齐和 offset 叠加语义还没有和公开 API 对齐。

Line 394 在 align 未传时回退到了 start,所以 scrollTo({ index, offset }) 会跳成顶对齐,而不是这次 API 声明的默认 nearest。另外 Line 386 在目标行已经可见时直接返回 currentTop,会把 align: 'nearest' 下的 offset 静默吞掉。这里更稳妥的做法是先算“不带 offset 的基准位置”,最后统一再 + offset

🔧 建议修改
-                if (align === 'nearest') {
-                  const targetWithOffset = elementTop + offset;
-                  const targetBottomWithOffset = elementBottom + offset;
-
-                  if (targetWithOffset < currentTop) {
-                    targetTop = targetWithOffset;
-                  } else if (targetBottomWithOffset > viewportBottom) {
-                    targetTop = targetBottomWithOffset - containerHeight;
-                  } else {
-                    targetTop = currentTop;
-                  }
-                } else {
-                  const alignMap: Record<string, number> = {
+                const mergedAlign = align ?? 'nearest';
+
+                if (mergedAlign === 'nearest') {
+                  let baseTop = currentTop;
+
+                  if (elementTop < currentTop) {
+                    baseTop = elementTop;
+                  } else if (elementBottom > viewportBottom) {
+                    baseTop = elementBottom - containerHeight;
+                  }
+
+                  targetTop = baseTop + offset;
+                } else {
+                  const alignMap: Record<'start' | 'end' | 'center', number> = {
                     start: elementTop,
                     end: elementBottom - containerHeight,
                     center: elementTop - (containerHeight - elementHeight) / 2,
                   };
-                  targetTop = alignMap[align ?? 'start'] + offset;
+                  targetTop = alignMap[mergedAlign] + offset;
                 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Table.tsx` around lines 377 - 395, The current logic computes targetTop
mixed with offset and falls back to 'start' when align is undefined, and the
'nearest' branch returns currentTop without applying offset when the element is
already visible; change behavior so the default align is 'nearest' when align is
undefined and compute a baseline target (without offset) for all branches, then
add offset once at the end; specifically update the 'nearest' branch to set a
baseTargetTop (use elementTop, elementBottom, currentTop, viewportBottom,
containerHeight to decide baseTargetTop) instead of returning currentTop
directly, change the alignMap fallback from 'start' to 'nearest', and finally
set targetTop = baseTargetTop + offset (using the existing symbols elementTop,
elementBottom, elementHeight, containerHeight, currentTop, viewportBottom,
align, offset, targetTop).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/Table.tsx`:
- Around line 377-395: The current logic computes targetTop mixed with offset
and falls back to 'start' when align is undefined, and the 'nearest' branch
returns currentTop without applying offset when the element is already visible;
change behavior so the default align is 'nearest' when align is undefined and
compute a baseline target (without offset) for all branches, then add offset
once at the end; specifically update the 'nearest' branch to set a baseTargetTop
(use elementTop, elementBottom, currentTop, viewportBottom, containerHeight to
decide baseTargetTop) instead of returning currentTop directly, change the
alignMap fallback from 'start' to 'nearest', and finally set targetTop =
baseTargetTop + offset (using the existing symbols elementTop, elementBottom,
elementHeight, containerHeight, currentTop, viewportBottom, align, offset,
targetTop).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a5f6d899-b12b-4a48-94d1-b9f624dc1584

📥 Commits

Reviewing files that changed from the base of the PR and between 833f5ce and c71b494.

📒 Files selected for processing (3)
  • docs/examples/scrollY.tsx
  • docs/examples/virtual.tsx
  • src/Table.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/examples/scrollY.tsx

Use nullish coalescing for safer align fallback

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@zombieJ
Copy link
Copy Markdown
Member

zombieJ commented Apr 1, 2026

@gemini-code-assist CR again

Copy link
Copy Markdown
Contributor

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

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 an align parameter to the scrollTo method in the Table component, supporting both standard and virtualized tables. The implementation allows users to specify vertical alignment (start, center, end, nearest) when scrolling to a specific row by index or key. The logic for calculating scroll positions with offsets has been updated to respect these alignment options. Documentation, examples, and comprehensive tests have been added to cover the new functionality. Feedback suggests optimizing performance by moving static alignment mappings outside of the scrollTo function calls.

Comment on lines +390 to +394
start: elementTop,
end: elementBottom - containerHeight,
center: elementTop - (containerHeight - elementHeight) / 2,
};
targetTop = alignMap[align ?? 'start'] + offset;
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.

medium

The alignMap object is recreated on every call to scrollTo. For better performance, consider moving this mapping outside the function or using a constant.

Comment on lines +90 to +94
const alignMap: Record<string, 'top' | 'bottom' | 'auto'> = {
start: 'top',
end: 'bottom',
nearest: 'auto',
};
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.

medium

The alignMap object is recreated on every call to scrollTo. For better performance, consider moving this mapping outside the function or using a constant.

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 1, 2026

Codecov Report

❌ Patch coverage is 92.68293% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.05%. Comparing base (45f97df) to head (ec47eb8).

Files with missing lines Patch % Lines
src/Table.tsx 89.28% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1469      +/-   ##
==========================================
- Coverage   96.10%   96.05%   -0.06%     
==========================================
  Files          57       57              
  Lines        3442     3473      +31     
  Branches      637      642       +5     
==========================================
+ Hits         3308     3336      +28     
- Misses        129      132       +3     
  Partials        5        5              

☔ View full report in Codecov by Sentry.
📢 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.

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