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

Walkthrough

重构 Preview 组件的键盘导航:移除对 KeyCode 的依赖,改为基于 event.key 处理 'ArrowLeft' / 'ArrowRight',在触发左右切换时调用 event.preventDefault() 并调用对应 onActive;同时升级依赖 @rc-component/util 到 ^1.7.0。

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 | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题清晰准确地总结了主要变化:防止键盘切换图片时页面滚动,与代码变更内容完全相符。
Linked Issues check ✅ Passed 代码变更通过添加可编辑目标检查和使用event.preventDefault()来防止键盘事件导致的页面滚动,符合问题#56290的要求。
Out of Scope Changes check ✅ Passed 除了与键盘导航滚动防止相关的Preview组件更改和依赖更新外,没有发现超出范围的改动。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6273ace and 77acb0e.

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

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.

@socket-security
Copy link

socket-security bot commented Jan 13, 2026

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedeslint@​8.57.19710010050100
Addedrc-test@​7.1.3751007490100
Updatedless@​4.1.3 ⏵ 4.5.191 -610080 +191100
Addedfather@​4.6.13931008198100
Addeddumi@​2.4.21951008384100
Addedreact@​19.2.31001008497100
Updatedglob@​10.5.0 ⏵ 11.1.0100 +110010088100
Addedtypescript@​5.9.31001009010090
Addedreact-dom@​19.2.31001009298100

View full report

@socket-security
Copy link

socket-security bot commented Jan 13, 2026

Warning

Review the following alerts detected in dependencies.

According to your organization's Security Policy, it is recommended to resolve "Warn" alerts. Learn more about Socket for GitHub.

Action Severity Alert  (click "▶" to expand/collapse)
Warn High
Obfuscated code: npm entities is 91.0% likely obfuscated

Confidence: 0.91

Location: Package overview

From: ?npm/father@4.6.13npm/dumi@2.4.21npm/entities@4.5.0

ℹ Read more on: This package | This alert | What is obfuscated code?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: Packages should not obfuscate their code. Consider not using packages with obfuscated code.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/entities@4.5.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

View full report

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