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(Sender): add files param to the onPasteFile callback #505

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

Conversation

ztkuaikuai
Copy link
Contributor

@ztkuaikuai ztkuaikuai commented Jan 28, 2025

Why PR

onPasteFile 回调支持获取到黏贴的多个文件

link to: #504 #494

Summary by CodeRabbit

  • 新功能

    • 增强了文件粘贴功能,现在支持同时处理多个文件
    • 更新了文件粘贴事件处理,允许获取和上传多个文件
  • 文档更新

    • 更新了代码示例和 API 文档,反映了新的多文件粘贴能力
    • 修改了文档中的示例标签,从"粘贴图片"改为"粘贴文件"
  • 测试

    • 新增了针对粘贴事件的测试用例,确保多文件粘贴功能的正确性

Copy link
Contributor

coderabbitai bot commented Jan 28, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • components/sender/__tests__/__snapshots__/index.test.tsx.snap is excluded by !**/*.snap

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

概述

演练

此次更改主要修改了 Sender 组件的文件粘贴功能。更新后,组件现在支持一次性粘贴和处理多个文件,而不仅限于单个文件。修改涉及 onPasteFile 函数的实现、接口定义和相关文档,使其能够接收并处理完整的文件列表。

变更

文件 变更摘要
components/sender/demo/paste-image.md 更新了文件上传功能描述
components/sender/demo/paste-image.tsx 修改 onPasteFile 事件处理器,支持多文件上传
components/sender/index.en-US.md 更新 API 文档和代码示例标签
components/sender/index.tsx 更新 SenderProps 接口和 onInternalPaste 函数
components/sender/index.zh-CN.md 更新中文文档和 API 描述
components/sender/__tests__/index.test.tsx 添加新的测试用例以验证粘贴事件处理

可能相关的问题

可能相关的 PR

建议的审阅者

  • YumoImer

诗歌

兔子轻跳,代码飞扬
粘贴文件,不再单调
多文件上传,如春风般畅
代码优雅,用户欢畅 🐰📁


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

github-actions bot commented Jan 28, 2025

Preview is ready

Copy link

Walkthrough

This PR enhances the onPasteFile callback functionality by allowing it to handle multiple files pasted at once. The callback now receives both the first file and a list of all files, enabling batch processing of pasted files.

Changes

File Summary
components/sender/demo/paste-image.md, components/sender/index.en-US.md, components/sender/index.zh-CN.md Updated documentation to reflect changes in the onPasteFile callback to handle multiple files.
components/sender/demo/paste-image.tsx Modified the onPasteFile callback to iterate over a list of files and upload each one.
components/sender/index.tsx Changed the onPasteFile function signature to accept a list of files, and updated the internal paste handler to process multiple files.

onPasteFile(file);
// Get files
const files = e.clipboardData?.files;
if (files.length && onPasteFile) {

Choose a reason for hiding this comment

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

Ensure that files is checked for null or undefined before accessing files.length to prevent potential runtime errors.

Copy link

codecov bot commented Jan 28, 2025

Bundle Report

Bundle size has no change ✅

Copy link

codecov bot commented Jan 28, 2025

Codecov Report

Attention: Patch coverage is 0% with 3 lines in your changes missing coverage. Please review.

Project coverage is 91.45%. Comparing base (b88b550) to head (26b65a2).

Files with missing lines Patch % Lines
components/sender/index.tsx 0.00% 3 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main     #505   +/-   ##
=======================================
  Coverage   91.45%   91.45%           
=======================================
  Files          67       67           
  Lines        1462     1462           
  Branches      384      370   -14     
=======================================
  Hits         1337     1337           
  Misses        125      125           

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

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

🧹 Nitpick comments (2)
components/sender/demo/paste-image.tsx (1)

65-68: 建议添加错误处理和性能优化

建议对文件处理逻辑进行以下优化:

  1. 添加对空文件列表的检查
  2. 考虑在处理大量文件时的性能优化

建议修改实现如下:

-        onPasteFile={(_, files) => {
-          for (const file of files) {
-            attachmentsRef.current?.upload(file);
-          }
+        onPasteFile={(_, files) => {
+          if (!files?.length) return;
+          
+          // 使用 Array.from 转换 FileList 为数组,提高性能
+          Array.from(files).forEach(file => {
+            attachmentsRef.current?.upload(file);
+          });
           setOpen(true);
         }}
components/sender/index.en-US.md (1)

55-55: API 文档更新清晰地说明了新的回调参数

回调函数签名的更新很好地支持了多文件粘贴的功能:

  • firstFile 参数保持了向后兼容性
  • files 参数提供了对所有粘贴文件的访问
  • 使用 FileList 类型是处理多文件的标准做法

建议补充一下参数说明:

-| onPasteFile | Callback when paste files | (firstFile: File, files: FileList) => void | - | - |
+| onPasteFile | Callback when paste files | (firstFile: File, files: FileList) => void | - | - |
+
+> - `firstFile`: 第一个粘贴的文件,用于向后兼容
+> - `files`: 包含所有粘贴文件的 FileList 对象
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b88b550 and 9f4aeb6.

📒 Files selected for processing (5)
  • components/sender/demo/paste-image.md (1 hunks)
  • components/sender/demo/paste-image.tsx (1 hunks)
  • components/sender/index.en-US.md (2 hunks)
  • components/sender/index.tsx (2 hunks)
  • components/sender/index.zh-CN.md (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
components/sender/index.tsx

[warning] 236-236: components/sender/index.tsx#L236
Added line #L236 was not covered by tests


[warning] 238-238: components/sender/index.tsx#L238
Added line #L238 was not covered by tests

🔇 Additional comments (5)
components/sender/index.tsx (2)

56-56: 类型定义更新

onPasteFile 回调函数的类型定义已更新,支持多文件处理。


235-240: 建议增加测试覆盖并加强类型安全

代码覆盖率分析显示新增代码缺少测试覆盖。同时,建议加强类型安全性检查。

建议添加以下测试用例:

describe('Sender', () => {
  it('should handle multiple files on paste', () => {
    const onPasteFile = jest.fn();
    const files = [
      new File([''], 'test1.txt'),
      new File([''], 'test2.txt')
    ];
    
    // 模拟 paste 事件
    const event = new ClipboardEvent('paste', {
      clipboardData: new DataTransfer()
    });
    files.forEach(file => event.clipboardData.items.add(file));
    
    // 触发事件并验证回调
    render(<Sender onPasteFile={onPasteFile} />);
    fireEvent.paste(screen.getByRole('textbox'), event);
    
    expect(onPasteFile).toHaveBeenCalledWith(files[0], expect.any(FileList));
  });
});
✅ Verification successful

建议采纳代码评审意见

评审意见是合理的,原因如下:

  • 当前测试文件中确实缺少对粘贴文件功能的测试覆盖
  • 建议的测试用例符合项目现有的测试模式,使用了 React Testing Library
  • 虽然项目已启用严格的 TypeScript 配置,但代码中的 files.length 访问没有进行充分的空值检查,建议改进为:
const files = e.clipboardData?.files;
if (files?.length && onPasteFile) {
  onPasteFile(files[0], files);
  e.preventDefault();
}

建议按照评审意见添加测试用例并加强类型安全性检查。

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for test files related to Sender component
echo "=== Searching for Sender test files ==="
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts | grep -i sender

echo -e "\n=== Looking for paste event tests ==="
rg -l "ClipboardEvent|paste" -g "*.test.{ts,tsx}" -g "*.spec.{ts,tsx}"

echo -e "\n=== Checking TypeScript configuration ==="
cat tsconfig.json 2>/dev/null || echo "tsconfig.json not found"

echo -e "\n=== Looking for test setup files ==="
fd "jest|test" -e config.js -e config.ts

Length of output: 1689


Script:

#!/bin/bash
echo "=== Checking Sender test content ==="
cat components/sender/__tests__/index.test.tsx

echo -e "\n=== Checking other test files for paste patterns ==="
cat components/sender/__tests__/demo.test.ts
cat components/sender/__tests__/image.test.ts

Length of output: 4863

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 236-236: components/sender/index.tsx#L236
Added line #L236 was not covered by tests


[warning] 238-238: components/sender/index.tsx#L238
Added line #L238 was not covered by tests

components/sender/demo/paste-image.md (1)

3-3: 文档更新准确反映了新功能

文档更新清晰地说明了 onPasteFile 的新功能,包括多文件处理能力。

Also applies to: 7-7

components/sender/index.zh-CN.md (1)

28-28: API文档更新完整且准确

文档变更准确反映了API的更新:

  1. 示例标题从"黏贴图片"改为"黏贴文件",更好地反映了组件的通用性
  2. onPasteFile 回调函数的参数说明完整且清晰

Also applies to: 56-56

components/sender/index.en-US.md (1)

27-27: 示例标题更新准确反映了功能范围

示例标题从"Paste image"更改为"Paste files"更好地反映了组件的实际功能,因为现在支持粘贴多个文件而不仅仅是图片。

@YumoImer
Copy link
Collaborator

YumoImer commented Feb 7, 2025

单測覆盖下~

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

🧹 Nitpick comments (1)
components/sender/__tests__/index.test.tsx (1)

143-214: 测试用例实现完整,建议补充以下场景!

当前测试用例已经很好地覆盖了基本功能,包括:

  • 基础粘贴回调
  • 单文件粘贴
  • 无文件粘贴
  • 多文件粘贴

建议考虑添加以下测试场景:

  1. 文件类型验证(例如:非图片文件)
  2. 错误处理(例如:文件损坏)
  3. 大文件处理

示例代码:

it('should validate file type', () => {
  const onPasteFile = jest.fn();
  const { container } = render(<Sender onPasteFile={onPasteFile} />);

  const invalidFile = new File(['test'], 'test.txt', { type: 'text/plain' });
  const fileList = {
    length: 1,
    item: (idx: number) => (idx === 0 ? invalidFile : null),
  };

  const textarea = container.querySelector('textarea')!;
  fireEvent.paste(textarea, {
    clipboardData: {
      files: fileList,
      getData: () => '',
    },
  });

  // 验证是否正确处理了非图片文件
  expect(onPasteFile).not.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 26b65a2 and 15d2585.

📒 Files selected for processing (1)
  • components/sender/__tests__/index.test.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build preview
  • GitHub Check: test / react component workflow
  • GitHub Check: size
🔇 Additional comments (1)
components/sender/__tests__/index.test.tsx (1)

142-142: 测试套件结构清晰且组织良好!

测试套件遵循了最佳实践,将相关的粘贴事件测试用例进行了合理分组。

@ztkuaikuai
Copy link
Contributor Author

ztkuaikuai commented Feb 7, 2025

Hi Imer @YumoImer ,我尝试添加了测试用例来覆盖与 onPasteFile 相关的逻辑,然而 Snapshots 未通过,这是什么原因呢?(我对测试这部分属于是知识盲区,请帮我严格 CR 下🥹)

@ztkuaikuai
Copy link
Contributor Author

ztkuaikuai commented Feb 8, 2025

有两个 Action 失败了,我看了下是因为:

Please install `@rc-component/np` instead of `np`.

但我不知道如何进行修复

@ztkuaikuai ztkuaikuai closed this Feb 8, 2025
@ztkuaikuai ztkuaikuai reopened this Feb 8, 2025
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