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(Attachments): fix Attachments onRemove no work #555

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

Conversation

edison-tianhe
Copy link

@edison-tianhe edison-tianhe commented Feb 25, 2025

[issue](#554)

Summary by CodeRabbit

  • 新增功能

    • 附件组件现支持通过自定义回调控制文件删除。若删除操作不被允许(返回 false),文件将保留在列表中,提升了文件管理的灵活性。
  • 测试

    • 添加了自动化测试,确保在禁止删除操作时,文件仍维持在附件列表中。

Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

📝 Walkthrough

Walkthrough

此变更在 Attachments 组件中添加了新的 onRemove 属性,并修改了文件移除逻辑。新增逻辑中,调用 onRemove 回调以确定是否允许移除文件。当回调返回 false 时,文件不会被移除。此外,相应的测试用例也已添加,验证当 onRemove 返回 false 时文件确实不会从列表中删除。

Changes

文件路径 变更摘要
components/attachments/index.tsx 新增 onRemove 属性,并修改 onItemRemove 函数,在移除文件前调用 onRemove 回调,根据返回值决定是否取消移除。
components/attachments/tests/index.test.tsx 添加测试用例 "add and remove file but can stop remove",模拟文件添加后尝试移除,验证当 onRemove 返回 false 时文件不被移除。

Possibly related PRs

Suggested reviewers

  • YumoImer
  • afc163

Poem

我是一只快乐的小兔子在代码中奔跳,
测试和逻辑齐舞,确保内容绝不跑偏。
onRemove守护文件,防止意外离场,
每行代码如同跳跃,带来希望的光芒。
代码森林中欢笑声,我为变更歌一曲! 🐇✨


📜 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 cdd6a86 and 4e491cf.

📒 Files selected for processing (1)
  • components/attachments/index.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/attachments/index.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

Prepare preview

Copy link

Walkthrough

This pull request addresses an issue with the Attachments component where the onRemove function was not working as expected. The changes ensure that the onRemove function can now prevent the removal of a file if it returns false.

Changes

File Summary
components/attachments/tests/index.test.tsx Added a test case to verify that a file can be added and then prevented from being removed using the onRemove function.
components/attachments/index.tsx Modified the onItemRemove function to check the return value of onRemove and prevent file removal if it returns false.

file: item,
fileList: newFileList,
let currentFile: Attachment;
Promise.resolve(typeof onRemove === 'function' ? onRemove(item) : onRemove).then((ret) => {

Choose a reason for hiding this comment

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

Ensure that the onRemove function is properly handled as a promise to prevent any asynchronous issues. The current implementation correctly resolves the onRemove function and checks its return value to decide whether to proceed with file removal.

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

🔭 Outside diff range comments (1)
components/attachments/index.tsx (1)

26-49: ⚠️ Potential issue

缺少 onRemove 属性的类型定义

在组件的属性解构中添加了 onRemove 属性(第 68 行),但在 AttachmentsProps 接口中没有对应的类型定义。需要在接口中添加此属性的类型定义,以确保类型安全。

建议添加以下定义:

export interface AttachmentsProps extends Omit<UploadProps, 'fileList'> {
  prefixCls?: string;

  rootClassName?: string;
  rootStyle?: React.CSSProperties;

  style?: React.CSSProperties;
  className?: string;

  classNames?: Partial<Record<SemanticType, string>>;
  styles?: Partial<Record<SemanticType, React.CSSProperties>>;

  children?: React.ReactElement;

  disabled?: boolean;

  // ============= placeholder =============
  placeholder?: PlaceholderType | ((type: 'inline' | 'drop') => PlaceholderType);
  getDropContainer?: null | (() => HTMLElement | null | undefined);

  // ============== File List ==============
  items?: Attachment[];
  overflow?: FileListProps['overflow'];
+ onRemove?: (item: Attachment) => Promise<boolean> | boolean;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7085686 and cdd6a86.

📒 Files selected for processing (2)
  • components/attachments/__tests__/index.test.tsx (1 hunks)
  • components/attachments/index.tsx (2 hunks)
🔇 Additional comments (1)
components/attachments/__tests__/index.test.tsx (1)

56-77: 测试用例实现正确

新增的测试用例正确验证了 onRemove 返回 false 时文件不会被删除的功能。测试思路清晰,断言准确。

Comment on lines 128 to 146
const onItemRemove = (item: Attachment) => {
const newFileList = fileList.filter((fileItem) => fileItem.uid !== item.uid);
triggerChange({
file: item,
fileList: newFileList,
let currentFile: Attachment;
Promise.resolve(typeof onRemove === 'function' ? onRemove(item) : onRemove).then((ret) => {
// Prevent removing file
if (ret === false) {
return;
}

const newFileList = fileList.filter((fileItem) => fileItem.uid !== item.uid);

if (newFileList) {
currentFile = { ...item, status: 'removed' };

triggerChange({
file: currentFile,
fileList: newFileList,
});
}
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

优化文件移除处理函数的实现

当前实现存在几个问题需要改进:

  1. currentFile 变量声明后没有初始化,在 Promise 链中才被赋值,可能导致问题
  2. if (newFileList) 判断条件是多余的,因为 filter 操作始终会返回一个数组(可能为空)
  3. Promise 链中没有错误处理,如果 onRemove 回调抛出错误,将会默默失败

建议修改为:

const onItemRemove = (item: Attachment) => {
-  let currentFile: Attachment;
  Promise.resolve(typeof onRemove === 'function' ? onRemove(item) : onRemove)
+   .then((ret) => {
      // Prevent removing file
      if (ret === false) {
        return;
      }

      const newFileList = fileList.filter((fileItem) => fileItem.uid !== item.uid);
-
-     if (newFileList) {
-       currentFile = { ...item, status: 'removed' };
-
-       triggerChange({
-         file: currentFile,
-         fileList: newFileList,
-       });
-     }
+     const currentFile = { ...item, status: 'removed' };
+     
+     triggerChange({
+       file: currentFile,
+       fileList: newFileList,
+     });
    })
+   .catch((error) => {
+     console.error('Error occurred during file removal:', error);
+   });
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const onItemRemove = (item: Attachment) => {
const newFileList = fileList.filter((fileItem) => fileItem.uid !== item.uid);
triggerChange({
file: item,
fileList: newFileList,
let currentFile: Attachment;
Promise.resolve(typeof onRemove === 'function' ? onRemove(item) : onRemove).then((ret) => {
// Prevent removing file
if (ret === false) {
return;
}
const newFileList = fileList.filter((fileItem) => fileItem.uid !== item.uid);
if (newFileList) {
currentFile = { ...item, status: 'removed' };
triggerChange({
file: currentFile,
fileList: newFileList,
});
}
});
const onItemRemove = (item: Attachment) => {
Promise.resolve(typeof onRemove === 'function' ? onRemove(item) : onRemove)
.then((ret) => {
// Prevent removing file
if (ret === false) {
return;
}
const newFileList = fileList.filter((fileItem) => fileItem.uid !== item.uid);
const currentFile = { ...item, status: 'removed' };
triggerChange({
file: currentFile,
fileList: newFileList,
});
})
.catch((error) => {
console.error('Error occurred during file removal:', error);
});
};

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