Skip to content

Conversation

zombieJ
Copy link
Member

@zombieJ zombieJ commented Sep 23, 2025

Summary by CodeRabbit

  • Bug Fixes
    • 修复当触发目标(target)变化时未重新对齐的问题。现在目标更新后会自动触发对齐,避免弹层/浮层位置错位,提升交互稳定性。
  • Tests
    • 新增覆盖目标切换触发对齐的测试用例;每次测试后恢复所有 mock,确保用例相互独立与可靠。
  • Style
    • 轻微代码格式调整,不影响功能与对外接口。

Copy link

coderabbitai bot commented Sep 23, 2025

Walkthrough

在 UniqueProvider 中新增两个 useEffect,当 mergedOptions.target 变化时调用 onAlign;其余为格式化调整。测试新增用例验证切换不同 Trigger 的 target 时会触发 onAlign,并添加 afterEach 清理 mock。

Changes

Cohort / File(s) Summary
UniqueProvider 对齐触发与格式化
src/UniqueProvider/index.tsx
重排 props 解构格式;新增两个 React.useEffect 监听 mergedOptions?.target 变化并调用 onAlign;未改动导出或函数签名。
测试:目标变化触发 onAlign
tests/unique.test.tsx
新增测试覆盖切换不同 Trigger 打开时 onAlign 被调用;mock useAlign 的 onAlign;加入 afterEach 中的 jest.restoreAllMocks()。

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as App
  participant UP as UniqueProvider
  participant Eff as useEffect(依赖: mergedOptions.target)
  participant Align as onAlign(AlignEngine)
  participant Target as Target Element
  participant Popup as Popup

  App->>UP: 渲染(传入 mergedOptions.target)
  UP->>Eff: 注册副作用(依赖 target)
  Note over Eff: 初始或 target 变更
  Eff->>Align: 调用 onAlign()
  Align->>Target: 读取定位信息
  Align->>Popup: 计算并更新对齐
  Popup-->>App: 渲染已对齐状态
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • afc163

Poem

小兔拍拍耳,瞄准目标点,
target 一变更,onAlign 立刻见。
两钩副作用,轻推云与烟,
Popup 随风准,对齐不拖延。
测试敲小鼓:准!准!再确认。 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed 标题“fix: Trigger additional force align for target change”直接描述了此次提交在目标(target)变化时触发额外对齐的修复,准确对应 changeset 中新增的 useEffect 钩子。该标题简洁且聚焦主要改动,能让审阅者快速理解变更意图。措辞明确,没有包含无关噪音或模糊表述。
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch force-align

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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
Contributor

Summary of Changes

Hello @zombieJ, 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 resolves an issue where the alignment of components managed by UniqueProvider might not update automatically when their associated target element changes. By adding a useEffect dependency on the target property, the system now forces a re-alignment, ensuring consistent and accurate positioning of popups relative to their dynamic targets. A new test case has been added to validate this behavior.

Highlights

  • Alignment Fix: Introduced a useEffect hook in UniqueProvider to explicitly trigger re-alignment (onAlign) whenever the mergedOptions?.target property changes. This ensures that popups correctly adjust their position when their target element is updated.
  • New Test Case: Added a comprehensive test case to unique.test.tsx that verifies the onAlign function is invoked when the target element of a UniqueProvider changes, confirming the new alignment logic works as intended.
  • Test Cleanup Improvement: Enhanced test isolation by adding jest.restoreAllMocks() to the afterEach hook in unique.test.tsx, preventing mock leaks between tests.
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

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

codecov bot commented Sep 23, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.41%. Comparing base (3597803) to head (1f3855b).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #581      +/-   ##
==========================================
+ Coverage   95.97%   96.41%   +0.43%     
==========================================
  Files          17       17              
  Lines         945      948       +3     
  Branches      278      269       -9     
==========================================
+ Hits          907      914       +7     
+ Misses         38       34       -4     

☔ 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
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 identifies the need to re-align the popup when its target changes and implements this using a React.useEffect hook. A corresponding test case has been added to verify this new behavior, which is great. My only suggestion is to make the test's mock implementation more concise for better maintainability. Overall, this is a solid contribution.

Comment on lines +297 to +313
jest.spyOn(useAlignModule, 'default').mockImplementation((...args) => {
const originalResult = originalUseAlign(...args);
// Replace onAlign with our mock
return [
originalResult[0], // ready
originalResult[1], // offsetX
originalResult[2], // offsetY
originalResult[3], // offsetR
originalResult[4], // offsetB
originalResult[5], // arrowX
originalResult[6], // arrowY
originalResult[7], // scaleX
originalResult[8], // scaleY
originalResult[9], // alignInfo
mockOnAlign, // onAlign - our mock function
];
});
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The mock implementation for useAlign is quite verbose. While the comments are helpful, the approach of manually listing each element of the returned array is brittle if the hook's return signature changes. You can make this more concise and maintainable.

    jest.spyOn(useAlignModule, 'default').mockImplementation((...args) => {
      const result = originalUseAlign(...args);
      // The `onAlign` function is the 11th element in the returned array (index 10).
      return [...result.slice(0, 10), mockOnAlign];
    });

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

🧹 Nitpick comments (2)
src/UniqueProvider/index.tsx (1)

150-154: useEffect 依赖与健壮性:建议加入 onAlign 依赖并在无 target 时跳过调用

当前未将 onAlign 放入依赖,可能触发 hooks/exhaustive-deps 警告;且当 target 为空时仍调用 onAlign 没必要。建议最小改动如下:

-  React.useEffect(() => {
-    onAlign();
-  }, [mergedOptions?.target]);
+  React.useEffect(() => {
+    if (!mergedOptions?.target) return;
+    onAlign();
+  }, [mergedOptions?.target, onAlign]);
tests/unique.test.tsx (1)

290-366: 对默认导出的 spy 可能未实际接管调用(导入时机/绑定缓存),请验证或改为更稳妥的 mock

UniqueProvider 可能在模块加载时已缓存了 useAlign 的函数引用,随后在 it 内对模块 default 的 spy 不一定能替换该引用,导致用例成为“假阳性”或脆弱。建议至少增加一次断言,验证 spy 确实被调用;若失败,请改为在隔离模块中先 mock 再导入被测模块。

最小验证(在本用例内即可落地):

-    const { container } = render(<TestComponent />);
+    const { container } = render(<TestComponent />);
+    // 确认我们的 spy 已接管 useAlign(若此处失败,说明当前 spy 未生效)
+    expect(useAlignModule.default).toHaveBeenCalled();

更稳妥的方案(先 mock 再导入,避免导入时机问题;可将该用例改写为 isolateModules 形式):

// 伪代码示例:在 it 内部使用 isolateModules,先 doMock useAlign,再 require 被测组件
it('should call onAlign when target changes', async () => {
  const mockOnAlign = jest.fn();

  await jest.isolateModulesAsync(async () => {
    jest.doMock('../src/hooks/useAlign', () => {
      const actual = jest.requireActual('../src/hooks/useAlign');
      return {
        __esModule: true,
        default: (...args: any[]) => {
          const res = actual.default(...args);
          // 用 mock 替换返回元组中的 onAlign(索引 10)
          return [...res.slice(0, 10), mockOnAlign];
        },
      };
    });

    const React = require('react');
    const { render, fireEvent } = require('@testing-library/react');
    const { default: Trigger, UniqueProvider } = require('../src');
    const { awaitFakeTimer } = require('./util');

    // ... 按现有 TestComponent 逻辑渲染与断言 ...
  });

  expect(mockOnAlign).toHaveBeenCalled();
});
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3597803 and 1f3855b.

📒 Files selected for processing (2)
  • src/UniqueProvider/index.tsx (2 hunks)
  • tests/unique.test.tsx (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/unique.test.tsx (1)
tests/util.tsx (1)
  • awaitFakeTimer (97-104)
🔇 Additional comments (2)
src/UniqueProvider/index.tsx (1)

25-28: 仅格式化变更,语义不变,OK

tests/unique.test.tsx (1)

69-69: 测试隔离性提升,赞:恢复所有 mocks

@zombieJ zombieJ merged commit 5cf3dc6 into master Sep 24, 2025
10 checks passed
@zombieJ zombieJ deleted the force-align branch September 24, 2025 01:28
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.

1 participant