Skip to content

feat: accessibility improvements #363

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

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

Conversation

jon-cullison
Copy link

@jon-cullison jon-cullison commented Apr 10, 2025

Implements 2/3 of the proposed changes here:
ant-design/ant-design#53203

I did not implement the panel role change because there is already some logic around setting the panel role to "tabpanel" when in accordion mode, and the panel role = "region" is optional for a11y purposes.

  • Adds optional headingLevel prop which will wrap the collapse header in a header element
  • Adds a default id generated by uuid to the collapse which will be used to create ids for the child components in order to link the header and panel.
  • Adds optional id prop which will override the default id mentioned above

Summary by CodeRabbit

  • Style

    • 优化折叠组件头部样式,确保标准与禁用状态下显示统一。
  • 新功能

    • 引入自动生成唯一标识符功能,支持自定义 ID,提升组件稳定性与无障碍体验。
    • 增加了设置标题层级的选项,使显示层次更灵活友好。
    • 折叠面板头部增加 ARIA 角色与属性,增强无障碍支持。
  • Tests

    • 扩展了测试覆盖,验证 ID 与标题层级功能的正确性,从而提升了整体可靠性。

Copy link

vercel bot commented Apr 10, 2025

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

Name Status Preview Comments Updated (UTC)
collapse ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 7, 2025 1:15pm

Copy link

coderabbitai bot commented Apr 10, 2025

Walkthrough

此次变更主要包含对 Collapse 组件及其子组件(Panel、PanelContent)的增强改造,同时对样式文件和测试用例进行了相应更新。CSS 中扩展了 header 的选择器以支持包裹结构;组件中新增了通过 useId 自动生成 id 的逻辑,并引入了 headingLevel 属性用于辅助设置无障碍相关属性;接口定义中添加了新的 HeadingLevelType 类型;测试用例也更新以覆盖新增 id 与 headingLevel 的功能。

Changes

文件(s) 变更摘要
assets/index.less 扩展 header 选择器,新增 @{prefixCls}-header-wrapper > .@{prefixCls}-header 样式,统一应用常规及禁用状态下的样式。
src/Collapse.tsx
src/Panel.tsx
src/PanelContent.tsx
src/hooks/…/useItems.tsx
在组件中新增 id 自动生成(基于 useId)和 headingLevel 属性,更新属性传递及无障碍相关的 aria 属性设置。
src/interface.ts 新增 HeadingLevelType 类型(1~6),并在 CollapseProps 与 CollapsePanelProps 中添加 headingLevel 和(CollapseProps 的)id 属性。
tests/index.spec.tsx 更新测试用例,新增针对 id 与 headingLevel 的测试,并重构部分测试逻辑以提升可读性。

Sequence Diagram(s)

sequenceDiagram
    participant U as 用户
    participant C as Collapse组件
    participant H as useItems钩子
    participant P as Panel组件
    participant W as HeaderWrapper

    U->>C: 请求渲染 Collapse
    C->>C: 检查是否提供 id(无则使用 useId 生成)
    C->>H: 传递 id 与 headingLevel
    H->>P: 将 id(可能附加索引)和 headingLevel 传给各 Panel
    P->>W: 根据 headingLevel 包装 header
    W-->>P: 返回处理后的 header
Loading

Possibly related PRs

Poem

我是一只快乐的小兔子,
在代码森林里欢快奔跑,
ID 与标题层级轻轻织就,
无障碍世界更加美妙,
修改微小如花开一瞬,
让每行代码闪耀着光芒!
🥕 跟我一同庆祝这新希望!

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/Collapse.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "prettier" to extend from. Please check that the name of the config is correct.

The config "prettier" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

src/hooks/useItems.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "prettier" to extend from. Please check that the name of the config is correct.

The config "prettier" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

src/Panel.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "prettier" to extend from. Please check that the name of the config is correct.

The config "prettier" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

  • 1 others

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 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 af2984e and 55bc778.

⛔ Files ignored due to path filters (1)
  • tests/__snapshots__/index.spec.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (4)
  • src/Collapse.tsx (4 hunks)
  • src/Panel.tsx (4 hunks)
  • src/hooks/useItems.tsx (5 hunks)
  • tests/index.spec.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/hooks/useItems.tsx
  • src/Collapse.tsx
  • src/Panel.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/index.spec.tsx (2)
src/index.tsx (1)
  • Collapse (10-10)
src/interface.ts (1)
  • HeadingLevelType (5-5)
🔇 Additional comments (7)
tests/index.spec.tsx (7)

6-6: 新增了 HeadingLevelType 类型导入,支持无障碍特性

更新了导入语句以包含新的 HeadingLevelType 类型,用于支持无障碍标题级别功能。


82-86: 重构获取标题元素的方式

通过抽取 getHeader 函数来获取标题元素,提高了代码可读性和维护性。


208-231: 很好地实现了 ID 测试辅助函数

runIdTest 函数设计合理,可以一致性地测试 ID 传播到各个子组件的情况,并验证正确的 ARIA 属性设置。


232-255: 完善的组合模式 ID 测试

测试覆盖了默认 ID 生成和自定义 ID 两种情况,确保组件的无障碍性。


257-288: 全面的 items 属性模式 ID 测试

确保在使用 items 属性方式时 ID 也能正确地传播,测试覆盖全面。


291-336: 完整的标题级别测试

测试了所有有效的标题级别(1-6)和未定义情况,确保 aria-level 属性被正确设置,对于提高组件的无障碍性非常重要。


941-941: 为嵌套折叠面板添加 ID

为测试中的嵌套 Collapse 组件添加 ID,与新功能保持一致。

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch master
  • Post Copyable Unit Tests in Comment

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this 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.

src/Collapse.tsx Outdated
@@ -6,6 +6,7 @@ import useItems from './hooks/useItems';
import type { CollapseProps } from './interface';
import CollapsePanel from './Panel';
import pickAttrs from '@rc-component/util/lib/pickAttrs';
import { v4 as uuid4 } from 'uuid';
Copy link
Member

Choose a reason for hiding this comment

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

Can we try not to rely on additional third-party packages?

Copy link
Author

Choose a reason for hiding this comment

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

We do not need to add this - the purpose was to create a default ID that is unique across multiple react applications that are rendered at the same time. However, if a consumer needs that, they can pass in an ID so I will go ahead and remove this package.

@jon-cullison
Copy link
Author

@yoyo837 I removed the uuid package, ready for re-review.

@@ -71,6 +80,8 @@ const convertItemsToNodes = (items: ItemType[], props: Props) => {
collapsible={mergeCollapsible}
onItemClick={handleItemClick}
destroyInactivePanel={mergeDestroyInactivePanel}
headingLevel={headingLevel}
id={id ? `${id}__item-${index}` : undefined}
Copy link
Member

Choose a reason for hiding this comment

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

You can use rc-util useId hooks in Panel. It support to use user pass id and fallback with ReactID if not have.

</div>
{showArrow && iconNode}
<span
className={classNames(`${prefixCls}-title`, customizeClassNames?.title)}
Copy link
Member

@zombieJ zombieJ Apr 23, 2025

Choose a reason for hiding this comment

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

replace this with HeadingElement instead of span directly. It's no need to have additional HeaderWrapper.

Copy link
Author

@jon-cullison jon-cullison Apr 29, 2025

Choose a reason for hiding this comment

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

I can change HeaderWrapper, but replacing the span would not satisfy the a11y standards for collapse / accordion components. The heading element should wrap the header button, which is where HeaderWrapper is in this PR. Would you prefer it to be a div that is always present around the button, instead of conditionally rendered, but it only would have the heading role and aria-level when the prop is defined?

Copy link
Member

Choose a reason for hiding this comment

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

OK. So you can add on the rc-collapse-header directly.

Copy link
Author

@jon-cullison jon-cullison May 21, 2025

Choose a reason for hiding this comment

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

Update - the rc-collapse-header element gets the button role, so to satisfy the a11y standards for the header, I changed to a div element that always wraps rc-collapse-header and will conditionally have the heading role and aria-level props set.

@afc163
Copy link
Member

afc163 commented Apr 23, 2025

Trace #362

src/Collapse.tsx Outdated
@@ -77,6 +81,8 @@ const Collapse = React.forwardRef<HTMLDivElement, CollapseProps>((props, ref) =>
activeKey,
classNames: customizeClassNames,
styles,
headingLevel,
id: collapseId,
Copy link
Member

Choose a reason for hiding this comment

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

this is not id but parentId

src/Panel.tsx Outdated
@@ -85,20 +88,38 @@ const CollapsePanel = React.forwardRef<HTMLDivElement, CollapsePanelProps>((prop
...(['header', 'icon'].includes(collapsible) ? {} : collapsibleProps),
};

const HeaderWrapper = ({ children: headerWrapperChildren }: PropsWithChildren) => {
Copy link
Member

@zombieJ zombieJ May 16, 2025

Choose a reason for hiding this comment

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

HeaderWrapper not satisfied with our semantic rule. You can just assign the heading role on the rc-collapse-title element instead of create new element.

https://github.com/react-component/collapse/pull/363/files#r2092418393

@@ -142,6 +155,8 @@ const getNewChild = (
onItemClick: handleItemClick,
expandIcon,
collapsible: mergeCollapsible,
headingLevel,
id: id ? `${id}__item-${index}` : undefined,
Copy link
Member

Choose a reason for hiding this comment

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

use key instead of index

Copy link

vercel bot commented May 21, 2025

@jon-cullison is attempting to deploy a commit to the React Component Team on Vercel.

A member of the Team first needs to authorize it.

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.

4 participants