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

feat: add popupRender prop to support custom popup content #747

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

Zyf665
Copy link

@Zyf665 Zyf665 commented Feb 17, 2025

  • Add popupRender prop to Menu and SubMenu components
  • Support both global and individual SubMenu popup customization
  • popupRender receives node and info params for flexible rendering
  • Update types and context to support the new feature

This implements the RFC for customizable SubMenu popup content.

Summary by CodeRabbit

  • 新功能
    • 菜单及子菜单现支持自定义弹出内容渲染,提升了界面定制与交互体验。
    • 新示例展示了如何应用自定义弹出展示效果。
  • 文档
    • 添加了专门章节介绍自定义弹出效果,包括示例代码和使用指南。
  • 样式
    • 新增了弹出组件的样式,增强了视觉效果和交互体验。
  • 测试
    • 新增测试用例确保自定义弹出功能在各交互场景下稳定运行。

Copy link

coderabbitai bot commented Feb 17, 2025

Walkthrough

新增了关于自定义弹出层渲染的文档章节、示例代码及样式文件,同时在核心组件(Menu、SubMenu、MenuContext 和接口定义)中增加了对 popupRender 属性的支持,并移除一些废弃的属性。各部分变更协同实现了弹出层渲染自定义化,并伴随相应的单元测试以验证新功能的正确性。

Changes

文件 变更摘要
docs/demo/customPopupRender.md, docs/examples/customPopupRender.tsx, docs/examples/customPopupRender.less 增加自定义弹出层渲染的文档说明、示例组件及对应样式
src/Menu.tsx, src/SubMenu/index.tsx, src/context/MenuContext.tsx, src/interface.ts 扩展接口,新增 popupRender 属性支持自定义弹出内容,同时移除旧属性并优化渲染逻辑
tests/popupRender.test.tsx 新增测试用例,覆盖不同场景下 popupRender 的渲染行为

Sequence Diagram(s)

sequenceDiagram
    participant U as 用户
    participant M as Menu组件
    participant SM as 子菜单组件
    participant PR as popupRender函数
    participant D as 自定义渲染组件

    U->>M: 鼠标悬停或点击菜单项
    M->>SM: 通知显示子菜单
    SM->>PR: 检查并调用 popupRender(若定义)
    alt 使用自定义 popupRender
        PR->>D: 返回自定义渲染内容
        D-->>SM: 替换默认渲染
    else 未使用自定义
        SM-->>SM: 使用默认渲染
    end
    SM-->>M: 展示最终弹出层效果
Loading

Poem

我是一只跳跃的小兔子,
在代码森林中漫步嬉戏。
自定义弹窗闪耀如星辰,
每一行代码舞动着诗意。
让我们欢庆这灵动更新 🐰✨!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/SubMenu/index.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /.eslintrc.js
Error: Cannot find module '@umijs/fabric/dist/eslint'
Require stack:

  • /.eslintrc.js
  • /node_modules/.pnpm/@eslint[email protected]/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object. (/.eslintrc.js:2:21)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)
    at Module._load (node:internal/modules/cjs/loader:1127:12)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)
tests/popupRender.test.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Cannot read config file: /.eslintrc.js
Error: Cannot find module '@umijs/fabric/dist/eslint'
Require stack:

  • /.eslintrc.js
  • /node_modules/.pnpm/@eslint[email protected]/node_modules/@eslint/eslintrc/dist/eslintrc.cjs
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli-engine/cli-engine.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/eslint.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/eslint/index.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/lib/cli.js
  • /node_modules/.pnpm/[email protected]/node_modules/eslint/bin/eslint.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object. (/.eslintrc.js:2:21)
    at Module._compile (node:internal/modules/cjs/loader:1546:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1691:10)
    at Module.load (node:internal/modules/cjs/loader:1317:32)
    at Module._load (node:internal/modules/cjs/loader:1127:12)
    at TracingChannel.traceSync (node:diagnostics_channel:315:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:217:24)
    at Module.require (node:internal/modules/cjs/loader:1339:12)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 88b303a and f8124dd.

📒 Files selected for processing (2)
  • src/SubMenu/index.tsx (6 hunks)
  • tests/popupRender.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/SubMenu/index.tsx
  • tests/popupRender.test.tsx

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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 (7)
src/interface.ts (1)

146-149: 建议改进 PopupRender 类型定义

info 参数中的 item 类型使用 any 过于宽松,建议使用更具体的类型定义。

建议如下修改:

 export type PopupRender = (
   node: React.ReactElement,
-  info: { item: any; keys: string[] },
+  info: { item: SubMenuType | MenuItemType; keys: string[] },
 ) => React.ReactNode;
docs/examples/customPopupRender.tsx (2)

70-82: 建议优化 popupRender 函数的性能

当前实现在每次渲染时都会重新创建函数,建议使用 useCallback 来优化性能。

建议如下修改:

+import { useCallback } from 'react';

 const NavigationDemo = () => {
-  const popupRender = (node: ReactElement) => (
+  const popupRender = useCallback((node: ReactElement) => (
     <div className="navigation-popup">
       <div className="navigation-grid">
         {React.Children.map(node.props.children.props.children, child => (
           <div className="navigation-item">
             {React.cloneElement(child, {
               className: `${child.props.className || ''} navigation-menu-item`,
             })}
           </div>
         ))}
       </div>
     </div>
-  );
+  ), []);

7-69: 建议添加 menuItems 的类型定义

为了提高代码的可维护性和类型安全性,建议为 menuItems 添加明确的类型定义。

建议如下修改:

+import type { ItemType } from 'rc-menu';

 const NavigationDemo = () => {
-  const menuItems = [
+  const menuItems: ItemType[] = [
     {
       key: 'home',
       label: 'Home',
     },
     // ...
   ];
tests/popupRender.test.tsx (1)

6-175: 建议增加更多边缘测试用例

当前的测试覆盖了基本功能,但建议添加以下场景的测试:

  1. 处理 popupRender 返回 null 的情况
  2. 测试动态切换 popupRender 函数
  3. 测试错误处理场景

我可以帮助生成这些额外的测试用例,是否需要?

src/SubMenu/index.tsx (1)

281-303: 建议优化 renderPopupContent 函数的实现

当前实现逻辑清晰,但建议考虑以下优化:

  1. 添加对 mergedPopupRender 返回值的类型检查
  2. 考虑添加错误边界处理

建议修改实现如下:

 const mergedPopupRender = propsPopupRender || contextPopupRender;

 const renderPopupContent = () => {
   const triggerMode = triggerModeRef.current;
   const originNode = (
     <MenuContextProvider
       mode={triggerMode === 'horizontal' ? 'vertical' : triggerMode}
     >
       <SubMenuList id={popupId} ref={popupRef}>
         {children}
       </SubMenuList>
     </MenuContextProvider>
   );

+  try {
     if (mergedPopupRender) {
-      return mergedPopupRender(originNode, {
+      const customNode = mergedPopupRender(originNode, {
         item: props,
         keys: connectedPath,
       });
+      return React.isValidElement(customNode) ? customNode : originNode;
     }
     return originNode;
+  } catch (error) {
+    console.error('Failed to render custom popup content:', error);
+    return originNode;
+  }
 };
docs/examples/customPopupRender.less (2)

1-44: 建议优化 navigation-popup 样式实现

当前导航弹出层样式结构清晰,但建议考虑以下优化:

  1. 考虑添加媒体查询以支持响应式布局
  2. 建议使用 CSS 变量管理颜色和间距值
  3. 可以添加暗色主题支持

建议添加如下样式:

+:root {
+  --navigation-popup-padding: 24px;
+  --navigation-popup-bg: #fff;
+  --navigation-popup-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
+  --navigation-text-secondary: rgba(0, 0, 0, 0.45);
+}

+@media (max-width: 768px) {
+  .navigation-popup {
+    min-width: 100%;
+    
+    .navigation-grid {
+      grid-template-columns: 1fr;
+    }
+  }
+}

+@media (prefers-color-scheme: dark) {
+  :root {
+    --navigation-popup-bg: #1f1f1f;
+    --navigation-popup-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
+    --navigation-text-secondary: rgba(255, 255, 255, 0.45);
+  }
+}

46-76: 建议优化 panel-popup 样式实现

面板弹出层样式实现简洁,但建议:

  1. 使用 CSS 变量统一管理样式值
  2. 添加过渡动画提升交互体验
  3. 考虑无障碍支持

建议添加如下样式:

+.panel-popup {
+  /* ... existing styles ... */
+
+  .panel-content {
+    .rc-menu-item {
+      /* ... existing styles ... */
+
+      transition: background-color 0.2s ease;
+
+      &:focus-visible {
+        outline: 2px solid #1890ff;
+        outline-offset: -1px;
+      }
    }
  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4960fa9 and 378bf74.

📒 Files selected for processing (8)
  • docs/demo/customPopupRender.md (1 hunks)
  • docs/examples/customPopupRender.less (1 hunks)
  • docs/examples/customPopupRender.tsx (1 hunks)
  • src/Menu.tsx (4 hunks)
  • src/SubMenu/index.tsx (6 hunks)
  • src/context/MenuContext.tsx (2 hunks)
  • src/interface.ts (1 hunks)
  • tests/popupRender.test.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/demo/customPopupRender.md
🔇 Additional comments (3)
src/context/MenuContext.tsx (1)

11-11: 代码变更看起来不错!

新增的 popupRender 属性和相关类型导入的位置恰当,保持了代码的整洁性和可维护性。

Also applies to: 50-50

src/SubMenu/index.tsx (1)

7-7: 新增 PopupRender 类型导入和接口定义

popupRender 属性的添加增强了 SubMenu 组件的自定义能力,使其能够支持自定义弹出层内容渲染。

Also applies to: 39-39

src/Menu.tsx (1)

34-34: 完善 Menu 组件的 PopupRender 支持

popupRender 属性的添加使 Menu 组件能够在全局层面支持自定义弹出层渲染,与 SubMenu 组件形成完整的自定义渲染体系。

Also applies to: 163-163

node: ReactElement,
info: { item: any; keys: string[] },
) => {
const isSecondLevel = info.keys.length == 2;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

修复相等性比较

使用 == 进行相等性比较不是最佳实践,建议使用 ===

建议如下修改:

-    const isSecondLevel = info.keys.length == 2;
+    const isSecondLevel = info.keys.length === 2;

Also applies to: 114-114

const mergedPopupRender = propsPopupRender || contextPopupRender;

// renderPopupContent
const renderPopupContent = () => {
Copy link
Member

Choose a reason for hiding this comment

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

看起来不用封装成一个函数,如果为了代码结构可以考虑直接改成 useMemo

import type { ReactElement } from 'react';

describe('Menu PopupRender Tests', () => {
// 基础测试数据
Copy link
Member

Choose a reason for hiding this comment

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

都用英文~

</SubMenu>
</Menu>,
);
fireEvent.mouseEnter(screen.getByText('Test'));
Copy link
Member

Choose a reason for hiding this comment

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

不用这么复杂,直接 Menu 受控展开 key 就行了,我们只需要测 render,交互不用测

Copy link

codecov bot commented Feb 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 99.59%. Comparing base (4960fa9) to head (f8124dd).
Report is 3 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #747   +/-   ##
=======================================
  Coverage   99.59%   99.59%           
=======================================
  Files          27       27           
  Lines         738      748   +10     
  Branches      202      206    +4     
=======================================
+ Hits          735      745   +10     
  Misses          3        3           

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

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