Skip to content

Conversation

@cactuser-Lu
Copy link

@cactuser-Lu cactuser-Lu commented Dec 23, 2025

fix: ant-design/ant-design#56290

Summary by CodeRabbit

发布说明

  • Bug Fixes

    • 优化预览的键盘交互:ESC 会阻止默认行为并关闭预览;在显示左右切换控件时使用箭头键进行前后切换并阻止默认行为以确保一致响应;当焦点位于可编辑元素时,键盘快捷键将被忽略以避免干扰输入。
    • 键盘判断改为基于键名以提升兼容性与可维护性。
  • Chores

    • 更新依赖版本以保证稳定性。

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Dec 23, 2025

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

coderabbitai bot commented Dec 23, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

在 Preview 组件的键盘处理里移除对 KeyCode 的依赖,改为基于 event.key 检测左右箭头('ArrowLeft'/'ArrowRight'),当可左右切换时对左右键调用 event.preventDefault() 并触发相应切换;同时更新 @rc-component/util 依赖版本。

Changes

Cohort / File(s) Change summary
Preview 键盘处理
src/Preview/index.tsx
去除对 KeyCode 的导入和判断,改用 event.key === 'ArrowLeft' / 'ArrowRight';在左右导航分支中添加 event.preventDefault() 并调用 onActive(-1)/onActive(+1);其它非导航/非打开状态行为保持不变。
依赖更新
package.json
将依赖 @rc-component/util^1.3.0 升级到 ^1.7.0

Sequence Diagram(s)

(不生成序列图 — 更改限于单组件内部键盘处理,参与方少于 3 个)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 分钟

Possibly related PRs

Suggested reviewers

  • zombieJ

兔兔诗歌

🐰 轻踏键盘听风响,
左右一按不再慌,
可编辑处我绕行,
预览安静抱萝卜,
小窗稳坐乐洋洋 🥕

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题准确反映了主要变更:通过键盘切换图片时防止页面滚动,与代码变更(添加event.preventDefault())和问题描述相符。
Linked Issues check ✅ Passed PR通过在keyboard事件处理中添加event.preventDefault()来解决issue #56290中报告的页面滚动问题,满足预期行为需求。
Out of Scope Changes check ✅ Passed 所有变更都与问题修复相关:键盘事件处理更新和依赖版本提升,均在scope内。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @cactuser-Lu, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a user experience issue within the image preview component by preventing default browser actions when specific keyboard keys are pressed. Previously, using keys like 'Escape' or arrow keys for navigation could inadvertently trigger page scrolling. The changes ensure that these keyboard inputs are exclusively handled by the image preview, providing a smoother and more predictable interaction for users.

Highlights

  • Keyboard Event Handling: Implemented event.preventDefault() for keyboard interactions within the image preview component to stop default browser behaviors.
  • Bug Fix: Resolved an issue where pressing ESC, LEFT, or RIGHT arrow keys could cause unintended page scrolling or other default browser actions while using the image preview.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
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 correctly fixes the issue of page scrolling when switching images using the keyboard by adding event.preventDefault(). The change is straightforward and effective. I've also added a suggestion to refactor the keyboard event handling logic using a switch statement, which could improve code readability and maintainability. Overall, great job on fixing this bug.

Comment on lines 335 to 348
if (keyCode === KeyCode.ESC) {
event.preventDefault();
onClose?.();
}

if (showLeftOrRightSwitches) {
if (keyCode === KeyCode.LEFT) {
event.preventDefault();
onActive(-1);
} else if (keyCode === KeyCode.RIGHT) {
event.preventDefault();
onActive(1);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

While the current implementation is correct, you could refactor this block to use a switch statement. This would make the code more structured, readable, and easier to maintain, especially if more keyboard shortcuts are added in the future. It also helps to reduce some code duplication by grouping the LEFT and RIGHT arrow key handling.

      switch (keyCode) {
        case KeyCode.ESC:
          event.preventDefault();
          onClose?.();
          break;
        case KeyCode.LEFT:
        case KeyCode.RIGHT:
          if (showLeftOrRightSwitches) {
            event.preventDefault();
            onActive(keyCode === KeyCode.LEFT ? -1 : 1);
          }
          break;
        default:
          break;
      }

Copy link
Member

Choose a reason for hiding this comment

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

+1

Copy link
Author

Choose a reason for hiding this comment

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

OK

@codecov
Copy link

codecov bot commented Dec 23, 2025

Codecov Report

❌ Patch coverage is 84.61538% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.02%. Comparing base (d3985c4) to head (1885625).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
src/Preview/index.tsx 84.61% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #493      +/-   ##
==========================================
- Coverage   99.41%   99.02%   -0.39%     
==========================================
  Files          17       17              
  Lines         509      515       +6     
  Branches      152      155       +3     
==========================================
+ Hits          506      510       +4     
- Misses          3        5       +2     

☔ 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.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes an issue where using keyboard shortcuts (ESC, LEFT, RIGHT arrows) in the image preview component would trigger unwanted page scrolling. The fix adds event.preventDefault() calls to the keyboard event handler to prevent default browser behavior while maintaining the intended preview functionality.

Key Changes

  • Added event.preventDefault() for ESC key to prevent default behavior when closing preview
  • Added event.preventDefault() for LEFT and RIGHT arrow keys to prevent page scrolling when switching between images

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 336 to 346
event.preventDefault();
onClose?.();
}

if (showLeftOrRightSwitches) {
if (keyCode === KeyCode.LEFT) {
event.preventDefault();
onActive(-1);
} else if (keyCode === KeyCode.RIGHT) {
event.preventDefault();
onActive(1);
Copy link

Copilot AI Dec 23, 2025

Choose a reason for hiding this comment

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

The keyboard event handling behavior, including the preventDefault calls, lacks test coverage. Consider adding tests to verify that:

  1. ESC key closes the preview and prevents default browser behavior
  2. LEFT/RIGHT arrow keys switch between images when showLeftOrRightSwitches is true
  3. preventDefault is properly called to prevent page scrolling

This would help ensure the fix for issue #56290 is properly validated and prevent regressions.

Copilot uses AI. Check for mistakes.
@aojunhao123
Copy link
Contributor

最好是等我这个pr #494 后再做你这个问题的修复吧,因为涉及到了portal侧的改动 @cactuser-Lu

@cactuser-Lu cactuser-Lu reopened this Dec 30, 2025
Copy link

@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)
src/Preview/index.tsx (1)

336-342: 建议将 preventDefault() 调用移到 onActive() 之前。

当前实现在调用 onActive() 之后才调用 event.preventDefault()。虽然这样可以正常工作(因为 onActive 只是更新状态),但更好的做法是先调用 preventDefault(),这样可以:

  1. 更早地阻止默认滚动行为
  2. 使代码意图更清晰
  3. 符合事件处理的最佳实践
🔎 建议的调整
       if (keyCode === KeyCode.LEFT) {
+        event.preventDefault();
         onActive(-1);
-        event.preventDefault();
       } else if (keyCode === KeyCode.RIGHT) {
+        event.preventDefault();
         onActive(1);
-        event.preventDefault();
       }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1885625 and deb3bfe.

📒 Files selected for processing (2)
  • package.json
  • src/Preview/index.tsx
✅ Files skipped from review due to trivial changes (1)
  • package.json

Copy link

@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)
src/Preview/index.tsx (1)

335-335: 考虑在执行操作之前调用 preventDefault。

event.preventDefault() 移至 onActive() 之前可以更清晰地表达意图:先阻止默认行为,再执行自定义操作。虽然当前代码功能正常,但这样的顺序更符合最佳实践。

🔎 建议的调整
       if (showLeftOrRightSwitches) {
         if (event.key === 'ArrowLeft') {
-          onActive(-1);
           event.preventDefault();
+          onActive(-1);
         } else if (event.key === 'ArrowRight') {
-          onActive(1);
           event.preventDefault();
+          onActive(1);
         }
       }

Also applies to: 338-338

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between deb3bfe and adf7f18.

📒 Files selected for processing (1)
  • src/Preview/index.tsx
🔇 Additional comments (1)
src/Preview/index.tsx (1)

330-342: Portal 组件可能不支持 onEsc 属性。

根据对 @rc-component/portal 官方文档的调查,该库的公开 API 仅包含 opengetContainerautoLock 属性,不包括 onEsc。代码中使用的 onEsc: PortalProps['onEsc'] 属性可能基于未文档化或不存在的 API,存在以下问题:

  1. @rc-component/portal 官方文档中无 onEsc 属性支持
  2. package.json 中指定的版本 "^2.1.2" 在 npm 注册表中不存在(最新版本为 v2.0.0)
  3. 当前实现可能依赖于不受支持或不稳定的 API

建议检查是否需要在组件内部自行处理 ESC 键事件,而不是依赖 Portal 组件提供此功能。

Likely an incorrect or invalid review comment.

Comment on lines +333 to 339
if (event.key === 'ArrowLeft') {
onActive(-1);
} else if (keyCode === KeyCode.RIGHT) {
event.preventDefault();
} else if (event.key === 'ArrowRight') {
onActive(1);
event.preventDefault();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

在可编辑元素中时,应跳过方向键处理。

当前实现在按下方向键时总是会切换图片,即使用户正在输入框、文本域或其他可编辑元素中输入内容。这会导致用户在编辑文本时意外触发图片切换,影响用户体验。

建议在处理方向键之前检查事件目标是否为可编辑元素:

🔎 建议的修复方案

在文件顶部添加辅助函数:

+const isEditableTarget = (target: EventTarget | null): boolean => {
+  if (!target || !(target instanceof Element)) return false;
+  const tagName = target.tagName;
+  if (tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') {
+    return true;
+  }
+  if (target instanceof HTMLElement && target.isContentEditable) {
+    return true;
+  }
+  return false;
+};
+
 const Preview: React.FC<PreviewProps> = props => {

然后在键盘事件处理中使用:

   const onKeyDown = useEvent((event: KeyboardEvent) => {
     if (open) {
+      if (isEditableTarget(event.target)) {
+        return;
+      }
       if (showLeftOrRightSwitches) {
         if (event.key === 'ArrowLeft') {
           onActive(-1);

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/Preview/index.tsx around lines 333 to 339, the ArrowLeft/ArrowRight
handler always changes images even when the user is focused in an editable
element; add a small helper (e.g., isEditableTarget) near the top of the file
that returns true for INPUT, TEXTAREA, elements with contentEditable="true" (and
optionally selects, or elements with role="textbox"), and update the keyboard
handler to short-circuit and do nothing when isEditableTarget(event.target) is
true before calling onActive and preventDefault.

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.

Image 键盘切换图片,外部元素会跟着滚动

3 participants