Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bubble auto scroll #327

Closed
wants to merge 2 commits into from

Conversation

anzhou99
Copy link
Contributor

@anzhou99 anzhou99 commented Dec 9, 2024

原Bubble.List中的autoScroll逻辑异常:无法正常自动滚动到新消息最底部(关联issue:https://github.com/ant-design/x/issues/317)。

解决方案: 使用MutationObserver机制,重写了滚动逻辑代码

原代码表现:
20241209115750_rec_
现代码表现:
20241209115851_rec_

Summary by CodeRabbit

  • 新功能

    • 引入了自动滚动功能,确保消息容器在添加新消息时自动滚动到底部。
    • 新增了 manualScrollToBottom 方法,以便用户可以程序化地滚动到容器底部。
  • 改进

    • 优化了滚动管理逻辑,简化了滚动到底部的实现,提升了组件对数据变化的响应能力。

Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

📝 Walkthrough

Walkthrough

此次更改涉及BubbleList组件的多个修改。引入了新的自定义钩子useAutoScrollToBottom,以管理自动滚动行为,替代了之前依赖状态更新的手动滚动逻辑。移除了updateCount状态变量,简化了新数据添加时的滚动逻辑。更新了onInternalScroll函数,允许1像素的容差来判断滚动是否到达底部,增强了滚动检测的准确性。

Changes

文件路径 更改摘要
components/bubble/BubbleList.tsx 引入并使用useAutoScrollToBottom钩子,移除updateCount,简化滚动逻辑,更新onInternalScroll以增强滚动检测。
components/bubble/hooks/useAutoScrollToBottom.ts 新增自定义钩子useAutoScroll,用于自动滚动消息容器,提供manualScrollToBottom方法。

Possibly related PRs

  • refactor: Bubble style #314: 此PR涉及Bubble组件的样式,与BubbleList组件在滚动管理和对数据变化的响应方面的修改直接相关。两个PR都专注于增强Bubble组件的功能和用户体验。

Suggested reviewers

  • YumoImer
  • afc163

🐰 在泡泡中跳跃,滚动如风,
自动下滑,信息不再沉默。
新钩子助力,轻松应对,
代码如诗,欢快而动。
兔子欢呼,变化真好,
让我们一起,享受这道! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented Dec 9, 2024

Preview is ready

Copy link

codecov bot commented Dec 9, 2024

Bundle Report

Changes will increase total bundle size by 487 bytes (0.31%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
antdx-array-push 156.29kB 487 bytes (0.31%) ⬆️

Copy link
Contributor

@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: 0

🧹 Outside diff range and nitpick comments (6)
components/bubble/hooks/useAutoScrollToBottom.ts (4)

8-13: 建议完善文档注释

建议在文档注释中补充以下内容:

  • 返回值的说明
  • 具体的使用示例
  • 自动滚动的触发条件

27-44: 建议优化 MutationObserver 的性能

当前实现在每次 DOM 变化时都会触发回调。建议:

  1. 使用防抖(debounce)来减少频繁触发
  2. 考虑使用 requestIdleCallback 在浏览器空闲时执行滚动
+ import { debounce } from 'lodash';

- const mutationObserver = new MutationObserver(() => {
+ const handleMutation = debounce(() => {
   const currentScrollHeight = container.scrollHeight;
   
   if (currentScrollHeight > prevScrollHeightRef.current) {
     if (shouldAutoScrollRef.current) {
       isAutoScrollingRef.current = true;
-      requestAnimationFrame(() => {
+      requestIdleCallback(() => {
         container.scrollTop = container.scrollHeight;
-        requestAnimationFrame(() => {
+        requestIdleCallback(() => {
           isAutoScrollingRef.current = false;
         });
       });
     }
     prevScrollHeightRef.current = currentScrollHeight;
   }
- });
+ }, 100);

+ const mutationObserver = new MutationObserver(handleMutation);

47-58: 建议添加滚动阈值配置

当前实现使用固定的 1px 误差值判断是否滚动到底部。建议:

  1. 将阈值作为可配置参数
  2. 添加注释说明为什么选择 1px 作为默认值

79-89: 建议增强手动滚动的错误处理

当前实现在 container 为空时直接返回。建议:

  1. 添加错误边界处理
  2. 考虑添加回调函数通知调用方滚动状态
- const manualScrollToBottom = () => {
+ const manualScrollToBottom = (callback?: (success: boolean) => void) => {
   if (container) {
     try {
       isAutoScrollingRef.current = true;
       container.scrollTop = container.scrollHeight;
       shouldAutoScrollRef.current = true;
       requestAnimationFrame(() => {
         isAutoScrollingRef.current = false;
+        callback?.(true);
       });
+    } catch (error) {
+      console.error('Failed to scroll to bottom:', error);
+      callback?.(false);
     }
+  } else {
+    callback?.(false);
   }
 };
components/bubble/BubbleList.tsx (2)

94-97: 建议增加错误处理和加载状态

在使用 useAutoScrollToBottom hook 时,建议:

  1. 处理 container 为 null 的情况
  2. 考虑添加加载状态指示器

133-133: 建议优化上下文更新逻辑

当前实现在每次气泡更新时都会触发滚动。建议:

  1. 添加条件判断,只在需要时触发滚动
  2. 考虑使用 useCallback 优化性能
const context = React.useMemo(
  () => ({
-   onUpdate: manualScrollToBottom,
+   onUpdate: React.useCallback(() => {
+     if (scrollReachEnd) {
+       manualScrollToBottom();
+     }
+   }, [scrollReachEnd]),
  }),
- [],
+ [scrollReachEnd],
);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 32ddbe7 and 81a551c.

📒 Files selected for processing (2)
  • components/bubble/BubbleList.tsx (3 hunks)
  • components/bubble/hooks/useAutoScrollToBottom.ts (1 hunks)
🔇 Additional comments (2)
components/bubble/hooks/useAutoScrollToBottom.ts (1)

72-76: 清理逻辑实现完善

清理函数正确处理了 MutationObserver 和事件监听器的销毁,值得肯定。

components/bubble/BubbleList.tsx (1)

90-91: 滚动检测逻辑与 hook 保持一致

使用 1px 误差值判断滚动位置的实现与 hook 保持一致,这是个好的做法。

Copy link

codecov bot commented Dec 9, 2024

Codecov Report

Attention: Patch coverage is 61.53846% with 15 lines in your changes missing coverage. Please review.

Project coverage is 90.45%. Comparing base (d218f8a) to head (81a551c).
Report is 34 commits behind head on main.

Files with missing lines Patch % Lines
components/bubble/hooks/useAutoScrollToBottom.ts 59.45% 15 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #327      +/-   ##
==========================================
- Coverage   91.13%   90.45%   -0.69%     
==========================================
  Files          66       67       +1     
  Lines        1421     1466      +45     
  Branches      378      382       +4     
==========================================
+ Hits         1295     1326      +31     
- Misses        126      140      +14     

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

@YumoImer
Copy link
Collaborator

YumoImer commented Dec 9, 2024

非常感谢您的贡献~

由于前置的 issue 不是一个 bug ,这个 PR 我暂时不打算做处理~

或者有其他的说明,证明这是个 bug ,您可以随时留言,非常感谢~

@anzhou99 anzhou99 closed this Dec 11, 2024
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