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: improve TabPane accessibility and content handling #780

Merged
merged 2 commits into from
Feb 17, 2025

Conversation

aojunhao123
Copy link
Contributor

@aojunhao123 aojunhao123 commented Feb 15, 2025

QQ_1739612834107

页签卡片复用了tabs组件,但是tabs children始终为空,需要特殊处理一下focus的情况

Summary by CodeRabbit

  • New Features
    • 优化了选项卡面板的焦点管理,现仅在面板处于激活状态且包含内容时设置为可聚焦,从而改善用户的导航体验。
  • Bug Fixes
    • 新增测试用例,确保当选项卡面板为空时不会获得焦点,从而增强可访问性。

Copy link

vercel bot commented Feb 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
tabs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 17, 2025 4:50am

Copy link

coderabbitai bot commented Feb 15, 2025

Walkthrough

该 PR 修改了 TabPane 组件,新增变量 hasContent 用于检测组件是否传入了 children。随后,根据组件是否激活(active)以及是否存在内容,调整 <div> 元素的 tabIndex 属性:若 active 且存在内容,则 tabIndex 设为 0;否则,保持为 -1。同时,新增了测试用例以验证当 tab 面板为空时,焦点不会转移到该面板上。

Changes

文件 更改内容
src/TabPanelList/TabPane.tsx - 新增变量 hasContent 检测 children 是否存在
- 根据 active 状态与内容存在性调整 tabIndex(active 且有内容设为 0,否则为 -1)
tests/accessibility.test.tsx - 新增测试用例 should not focus on tab panel when it is empty,验证空的 tab 面板不会获得焦点

Sequence Diagram(s)

sequenceDiagram
    participant C as Component
    participant T as TabPane
    C->>T: 渲染组件(提供 active 状态和 children)
    T->>T: 检查 hasContent(判断 children 是否存在)
    alt active 且 hasContent 为 true
        T->>T: 设置 tabIndex = 0
    else
        T->>T: 设置 tabIndex = -1
    end
Loading

Possibly related PRs

Suggested reviewers

  • zombieJ

Poem

嗨,我是一只淘气的小兔,
在代码丛中跳跃不停,
发现了一个焦点新奇境,
TabPane 跳跃出个新风景,
快乐编码,乐在心间!
🐰💻

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.

tests/accessibility.test.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react".

(The package "eslint-plugin-react" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react@latest --save-dev

The plugin "eslint-plugin-react" was referenced from the config file in ".eslintrc.js » /node_modules/.pnpm/@umijs[email protected]_jest@29.7.0_@types[email protected][email protected]/node_modules/@umijs/fabric/dist/eslint.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


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

codecov bot commented Feb 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 98.96%. Comparing base (1559c3b) to head (21b4d0d).
Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #780   +/-   ##
=======================================
  Coverage   98.96%   98.96%           
=======================================
  Files          18       18           
  Lines         771      772    +1     
  Branches      227      224    -3     
=======================================
+ Hits          763      764    +1     
  Misses          8        8           

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

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 (1)
src/TabPanelList/TabPane.tsx (1)

32-32: tabIndex 的处理逻辑改进了无障碍体验!

当前实现通过检查 activehasContent 来控制面板的焦点行为,这种方式符合 ARIA 最佳实践。

建议考虑为空面板添加 aria-empty 属性,以进一步提升无障碍体验。

 <div
   id={id && `${id}-panel-${tabKey}`}
   role="tabpanel"
   tabIndex={active && hasContent ? 0 : -1}
+  aria-empty={!hasContent}
   aria-labelledby={id && `${id}-tab-${tabKey}`}
   aria-hidden={!active}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1559c3b and 9a98cd2.

📒 Files selected for processing (1)
  • src/TabPanelList/TabPane.tsx (1 hunks)
🔇 Additional comments (1)
src/TabPanelList/TabPane.tsx (1)

26-26: 代码实现正确且简洁!

使用 React.Children.count 来检查子元素是否存在的方法非常恰当。这种实现方式简单有效,为后续的 tabIndex 逻辑奠定了基础。

return (
<div
id={id && `${id}-panel-${tabKey}`}
role="tabpanel"
tabIndex={active ? 0 : -1}
tabIndex={active && hasContent ? 0 : -1}
Copy link
Member

Choose a reason for hiding this comment

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

测试用例加一下

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 (1)
tests/accessibility.test.tsx (1)

272-282: 测试用例实现正确,建议增加更多场景测试

测试用例很好地验证了空面板的焦点行为。为了更全面地测试该功能,建议考虑添加以下场景:

  • 多个标签页混合测试(有内容和无内容的标签页)
  • 动态切换标签页内容(从有到无,从无到有)

建议添加如下测试用例:

it('should handle focus correctly with mixed content tabs', async () => {
  const user = userEvent.setup();
  const { getByRole } = render(
    <Tabs
      defaultActiveKey="1"
      items={[
        { key: '1', label: 'Tab1', children: 'Content 1' },
        { key: '2', label: 'Tab2', children: null },
        { key: '3', label: 'Tab3', children: 'Content 3' }
      ]}
    />,
  );

  // 验证有内容的面板可以获得焦点
  const tabPanel1 = getByRole('tabpanel', { name: /Tab1/i });
  await user.tab();
  await user.tab();
  expect(tabPanel1).toHaveFocus();

  // 验证空面板不会获得焦点
  const tabPanel2 = getByRole('tabpanel', { name: /Tab2/i });
  await user.keyboard('{ArrowRight}');
  await user.tab();
  expect(tabPanel2).not.toHaveFocus();
});

it('should handle focus correctly when content changes dynamically', async () => {
  const user = userEvent.setup();
  const Demo = () => {
    const [content, setContent] = React.useState('Initial content');
    return (
      <>
        <button onClick={() => setContent(null)}>Clear content</button>
        <button onClick={() => setContent('New content')}>Add content</button>
        <Tabs
          defaultActiveKey="1"
          items={[{ key: '1', label: 'Tab1', children: content }]}
        />
      </>
    );
  };

  const { getByRole } = render(<Demo />);

  // 验证初始状态下面板可以获得焦点
  const tabPanel = getByRole('tabpanel', { name: /Tab1/i });
  await user.tab();
  await user.tab();
  expect(tabPanel).toHaveFocus();

  // 清除内容后验证面板不会获得焦点
  await user.click(getByRole('button', { name: /Clear content/i }));
  await user.tab();
  await user.tab();
  expect(tabPanel).not.toHaveFocus();

  // 添加内容后验证面板可以获得焦点
  await user.click(getByRole('button', { name: /Add content/i }));
  await user.tab();
  await user.tab();
  expect(tabPanel).toHaveFocus();
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9a98cd2 and 21b4d0d.

📒 Files selected for processing (1)
  • tests/accessibility.test.tsx (1 hunks)

@zombieJ zombieJ merged commit 6d02218 into react-component:master Feb 17, 2025
9 checks passed
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