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: 增加浏览器中粘贴上传的功能,并增加相应的演示功能 #3151

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

Conversation

Jeff-Tian
Copy link

@Jeff-Tian Jeff-Tian commented Apr 4, 2025

🤔 这个变动的性质是?

  • 新特性提交
  • 日常 bug 修复
  • 站点、文档改进
  • 演示代码改进
  • 组件样式/交互改进
  • TypeScript 定义更新
  • 包体积优化
  • 性能优化
  • 功能增强
  • 国际化改进
  • 重构
  • 代码风格优化
  • 测试用例
  • 分支合并
  • 其他改动(是关于什么的改动?)

🔗 相关 Issue

💡 需求背景和解决方案

个人非常喜欢这个组件库,并用在了自己的小程序端和h5上。在浏览器中上传时,经常需要一个粘贴上传的功能,之前基于 2.7.7 的版本通过 patch-package 的方式已经在自己的站点上实现了,但是一旦升级就需要重新 patch,所以提个 PR,希望能够将此功能合并到上游,望采纳,不胜感激!

可能需要做一些代码修改,求大佬指点!

  1. 为 uploader 增加浏览器上的粘贴上传功能
  2. 用法:启用粘贴上传即可: <Uploader enablePasteUpload />
  3. 演示:
Screen.Recording.2025-04-04.at.11.55.35.mov

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

Summary by CodeRabbit

  • 新功能

    • 新增粘贴上传功能,允许用户通过粘贴方式直接上传图片文件。
    • 引入了新的示例组件,通过多语言展示该功能的使用效果。
    • 优化了图片处理,支持上传前预览,提升用户体验。
  • 文档

    • 更新了文档,详细介绍了粘贴上传功能的使用方法,并添加了相关翻译内容。

Copy link

coderabbitai bot commented Apr 4, 2025

Walkthrough

本次变更主要为 Uploader 组件新增粘贴上传功能及其相关演示、文档更新和内部文件处理优化。新增的测试用例验证了粘贴上传行为,Demo 展示中引入了新组件 Demo15 并增加对多语言翻译的支持,同时文档中添加了 enablePasteUpload 属性说明。内部上传逻辑也调整为更好地处理图片预览及文件读取流程。

Changes

文件路径 变更摘要
src/packages/uploader/__tests__/uploader.spec.tsx 新增“should handle paste upload”测试用例,模拟粘贴事件并验证 onChange 被调用及文件属性传递正确。
src/packages/uploader/demo.tsx
src/packages/uploader/demos/h5/demo15.tsx
在 Demo 中引入新组件 Demo15,添加 enablePasteUpload 功能展示及中、英、繁体翻译支持。
src/packages/uploader/doc.md 更新文档,新增粘贴上传功能说明及在 Props 表中添加 enablePasteUpload 属性(默认值 false)。
src/packages/uploader/uploader.taro.tsx 修改上传逻辑:使用空值合并运算符确保 file 对象正确传递,并在预览图片时用 FileReader 异步读取文件数据。
src/packages/uploader/uploader.tsx 为 Uploader 组件新增 enablePasteUpload 属性及默认值,增加 handlePaste 回调监听粘贴事件,实现粘贴上传功能。

Possibly related PRs

Suggested reviewers

  • xiaoyatong
  • Alex-huxiyang

Poem

我是一只快乐的小兔,
在代码森林里跳跃不停;
粘贴上传添新趣,
文件随风迎面亲;
每行代码皆心语,
未来跃然展宏图!
🐰 CodeRabbit 加油!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@github-actions github-actions bot added the 2.x Target branch 2.x label Apr 4, 2025
@Jeff-Tian Jeff-Tian force-pushed the feature/handle-paste-upload branch from b2c0079 to b741c74 Compare April 4, 2025 04:04
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 (5)
src/packages/uploader/demos/h5/demo15.tsx (1)

4-10: 示例代码实现良好,但可考虑添加提示说明

组件实现简洁明了,清晰地展示了粘贴上传功能。建议考虑添加一些提示文本,告知用户可以粘贴图片进行上传,这样能提高用户体验。

const Demo15 = () => {
  return (
    <>
-      <Uploader enablePasteUpload />
+      <Uploader enablePasteUpload uploadLabel="点击上传或粘贴图片" />
    </>
  )
}
src/packages/uploader/doc.md (1)

140-146: 文档更新清晰,建议增加使用说明

新增的粘贴上传功能文档说明简洁清晰。建议可以在演示说明中补充一些使用提示,例如如何使用粘贴功能(Ctrl+V 或右键粘贴)以及支持的图片格式等信息,这将有助于用户更好地理解和使用此功能。

src/packages/uploader/__tests__/uploader.spec.tsx (1)

290-331: 测试用例实现全面且规范

测试用例结构良好,采用了 arrange-act-assert 模式,清晰地验证了粘贴上传功能。模拟的 ClipboardEvent 和文件创建方式正确,期望值检查全面。

唯一可以改进的地方是考虑测试不同类型的文件(如非图片文件)或边缘情况的处理。

src/packages/uploader/uploader.tsx (1)

390-453: 粘贴上传功能实现。

粘贴上传功能实现得很完整,但有几点可以优化:

  1. 建议使用可选链操作符来避免潜在的空值引用
  2. 可以考虑添加对粘贴事件的错误处理
-      if (clipboardData.items && clipboardData.items.length) {
+      if (clipboardData?.items && clipboardData.items.length) {
-      } else if (clipboardData.files && clipboardData.files.length) {
+      } else if (clipboardData?.files && clipboardData.files.length) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 399-399: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 409-409: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

src/packages/uploader/uploader.taro.tsx (1)

431-446: 优化图片预览处理。

添加了对图片文件的预览处理,使用FileReader读取图片数据并设置URL和路径,这是一个很好的功能增强。不过,建议添加错误处理逻辑,以防读取文件失败。

        const reader = new FileReader()
+       reader.onerror = (error) => {
+         console.error('读取文件失败:', error)
+         executeUpload(fileItem, index)
+         results.push(fileItem)
+       }
        reader.onload = (event) => {
          fileItem.url = event.target?.result as string
          fileItem.path = event.target?.result as string
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a0e26ee and b741c74.

📒 Files selected for processing (6)
  • src/packages/uploader/__tests__/uploader.spec.tsx (1 hunks)
  • src/packages/uploader/demo.tsx (5 hunks)
  • src/packages/uploader/demos/h5/demo15.tsx (1 hunks)
  • src/packages/uploader/doc.md (2 hunks)
  • src/packages/uploader/uploader.taro.tsx (2 hunks)
  • src/packages/uploader/uploader.tsx (6 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/packages/uploader/demos/h5/demo15.tsx (2)
src/packages/uploader/uploader.taro.tsx (1)
  • Uploader (580-580)
src/packages/uploader/uploader.tsx (1)
  • Uploader (535-535)
🪛 Biome (1.9.4)
src/packages/uploader/uploader.tsx

[error] 399-399: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 409-409: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (9)
src/packages/uploader/doc.md (1)

204-204: 属性表格说明完整

属性表中的 enablePasteUpload 说明准确,类型和默认值描述清晰。

src/packages/uploader/demo.tsx (3)

18-18: 导入新组件的方式正确

新增 Demo15 组件的导入语句位置恰当,保持了与其他 Demo 组件相同的导入风格。


36-36: 多语言支持实现完整

为新功能添加了中文简体、中文繁体和英文三种语言的翻译,保持了应用的国际化一致性。

Also applies to: 52-52, 69-69


104-105: 界面集成方式符合现有模式

新功能的 UI 展示方式与现有其他功能一致,代码结构清晰。

src/packages/uploader/uploader.tsx (4)

74-74: 接口添加新属性,增强组件功能。

通过添加可选的enablePasteUpload属性,使组件支持从浏览器粘贴上传的功能,增强了用户体验。


104-104: 默认值配置合理。

enablePasteUpload的默认值设置为false是合理的,这样可以保持向后兼容性,用户需要显式开启该功能才能使用。


314-314: 文件读取逻辑优化。

修改后的代码确保了在读取文件后正确更新文件列表,这是一个很好的修复。


455-467: 事件监听器的生命周期管理。

事件监听器的添加和移除逻辑实现得很好,确保了在组件卸载时正确清理事件监听器,并且仅在enablePasteUploadtrue时才添加事件监听器。

src/packages/uploader/uploader.taro.tsx (1)

421-421: 改进对原始文件的处理。

使用空值合并运算符(??)来处理可能为空的originalFileObj是一个很好的改进,确保了在各种情况下都能正确地将文件添加到formData中。

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 (2)
src/packages/uploader/uploader.tsx (2)

390-453: 粘贴上传功能实现完善,但可优化代码健壮性

handlePaste 函数实现了粘贴上传的核心功能,逻辑完整且考虑了各种边界情况。但建议使用可选链操作符来提高代码健壮性。

建议对剪贴板数据的检查使用可选链操作符:

-      if (clipboardData?.items && clipboardData.items.length) {
+      if (clipboardData?.items?.length) {

以及:

-      } else if (clipboardData?.files && clipboardData.files.length) {
+      } else if (clipboardData?.files?.length) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 399-399: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 409-409: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


390-450: 考虑重构以减少代码重复

handlePaste 函数中的文件处理逻辑与 fileChange 函数中的逻辑有一定重复,特别是在处理 beforeUpload 和文件过滤方面。可以考虑提取一个共同的函数来处理这些相似逻辑。

可以考虑创建一个共用函数来处理文件上传逻辑:

const processFiles = (files: File[]) => {
  if (beforeUpload) {
    beforeUpload(files).then((f: Array<File> | boolean) => {
      if (typeof f === 'boolean') return
      
      const _files = filterFiles(new Array<File>().slice.call(f))
      if (_files.length) {
        readFile(_files)
        onChange?.([
          ...fileList,
          ..._files.map((file) => ({
            name: file.name,
            type: file.type,
            status: 'ready',
          })),
        ])
      }
    })
  } else {
    const _files = filterFiles(new Array<File>().slice.call(files))
    if (_files.length) {
      readFile(_files)
      onChange?.([
        ...fileList,
        ..._files.map((file) => ({
          name: file.name,
          type: file.type,
          status: 'ready',
        })),
      ])
    }
  }
}

然后在 handlePastefileChange 中调用这个函数。

🧰 Tools
🪛 Biome (1.9.4)

[error] 399-399: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 409-409: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b741c74 and 1de630c.

📒 Files selected for processing (3)
  • src/packages/uploader/demos/h5/demo15.tsx (1 hunks)
  • src/packages/uploader/doc.md (2 hunks)
  • src/packages/uploader/uploader.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/packages/uploader/demos/h5/demo15.tsx
  • src/packages/uploader/doc.md
🧰 Additional context used
🪛 Biome (1.9.4)
src/packages/uploader/uploader.tsx

[error] 399-399: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 409-409: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (7)
src/packages/uploader/uploader.tsx (7)

74-74: UploaderProps 接口新增的属性合理明确

新增的 enablePasteUpload 可选布尔属性符合接口设计规范,并且作为可选参数确保了向后兼容性,这对于现有代码不会造成破坏性影响。


104-104: 默认属性设置符合预期

enablePasteUpload 默认值设置为 false 是合理的,确保了现有使用组件的代码不会受到影响,用户需要显式启用该功能才能使用粘贴上传。


314-314: 图片预览处理逻辑优化

修改后的代码确保在读取到图片URL后立即更新文件列表,这样可以在图片文件完成读取后立即显示预览,改善了用户体验。


455-467: 事件监听器管理逻辑正确

useEffect 钩子正确地根据 enablePasteUpload 属性添加和移除粘贴事件监听器,确保只有在功能启用时才会响应粘贴事件。依赖数组包含了所有必要的依赖项,避免了闭包陷阱问题。


8-8: React 钩子使用得当

引入 useCallback 并使用它来优化 handlePaste 函数是一个很好的做法,避免了不必要的重新渲染。依赖数组包含了所有相关的变量,确保回调函数在依赖项变化时能够正确更新。

Also applies to: 390-453


154-154: 属性解构完整

enablePasteUpload 添加到解构的属性列表中,确保了新属性能够被组件正确访问和使用。


399-416: 粘贴事件处理全面

代码全面处理了两种可能的剪贴板数据格式(itemsfiles),并正确过滤只接受图片类型文件,这符合最佳实践。

🧰 Tools
🪛 Biome (1.9.4)

[error] 399-399: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 409-409: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

@github-actions github-actions bot added the action:review This PR needs more reviews (less than 2 approvals) label Apr 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
2.x Target branch 2.x action:review This PR needs more reviews (less than 2 approvals) size/L
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant