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: improve ApiSelect component #5075

Merged
merged 2 commits into from
Dec 9, 2024

Conversation

mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Dec 9, 2024

Description

改进ApiSelect组件,使之可以支持更多类型的组件包装。例子中提供了TreeSelect组件的Api封装。
close #5074

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Introduced the ApiTreeSelect component for enhanced hierarchical data selection.
    • Added new form fields utilizing ApiSelect and ApiTreeSelect components for dynamic API data integration.
  • Bug Fixes

    • Improved event handling for dropdown visibility in ApiSelect.
  • Documentation

    • Added comments to clarify component adaptations based on business requirements.
  • Chores

    • Enhanced properties in the api-select component for better API interaction and data handling.

@mynetfan mynetfan requested review from anncwb, vince292007 and a team as code owners December 9, 2024 04:21
Copy link

changeset-bot bot commented Dec 9, 2024

⚠️ No Changeset found

Latest commit: e8dddfe

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

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.

apps/web-antd/src/adapter/component/index.ts

Oops! Something went wrong! :(

ESLint: 9.16.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/node_modules/@vben/eslint-config/dist/index.mjs' imported from /eslint.config.mjs
at finalizeResolution (node:internal/modules/esm/resolve:257:11)
at moduleResolve (node:internal/modules/esm/resolve:914:10)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

Walkthrough

The pull request introduces a new component type, ApiTreeSelect, across multiple files in the codebase, enhancing the component adapter framework. This component is designed to work with tree data structures and is integrated into various forms, allowing for dynamic selection of menu items via API. The changes include updates to the initComponentAdapter function and the addition of new properties to existing components, ensuring backward compatibility while expanding functionality.

Changes

File Path Change Summary
apps/web-antd/src/adapter/component/index.ts Added ApiTreeSelect to ComponentType and implemented it in initComponentAdapter.
apps/web-ele/src/adapter/component/index.ts Added ApiTreeSelect to ComponentType and updated initComponentAdapter with its implementation.
apps/web-ele/src/views/demos/form/basic.vue Added ApiSelect and ApiTreeSelect components to the form schema with API integration.
apps/web-naive/src/adapter/component/index.ts Added ApiTreeSelect to ComponentType and implemented it in initComponentAdapter.
apps/web-naive/src/views/demos/form/basic.vue Added ApiSelect and ApiTreeSelect components to the form schema with API integration.
packages/effects/common-ui/src/components/api-select/api-select.vue Enhanced Props interface with new properties for better API interaction and data handling.
playground/src/adapter/component/index.ts Added ApiTreeSelect to ComponentType and implemented it in initComponentAdapter.
playground/src/views/examples/form/basic.vue Integrated ApiTreeSelect into the form schema with API data handling.

Assessment against linked issues

Objective Addressed Explanation
Implement ApiTreeSelect component as per design (5074)
Ensure integration with existing component framework (5074)
Maintain backward compatibility with existing components (5074)

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • vince292007
  • anncwb

"In the garden of code, I hop with delight,
A new ApiTreeSelect, oh what a sight!
With branches of data, and options galore,
Selecting with ease, who could ask for more?
So let’s celebrate this change, oh so bright,
For forms filled with magic, and components just right!" 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7929a52 and e8dddfe.

📒 Files selected for processing (5)
  • apps/web-antd/src/adapter/component/index.ts (2 hunks)
  • apps/web-ele/src/adapter/component/index.ts (2 hunks)
  • apps/web-naive/src/adapter/component/index.ts (2 hunks)
  • packages/effects/common-ui/src/components/api-select/api-select.vue (3 hunks)
  • playground/src/adapter/component/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/web-naive/src/adapter/component/index.ts
  • apps/web-antd/src/adapter/component/index.ts
🔇 Additional comments (8)
packages/effects/common-ui/src/components/api-select/api-select.vue (3)

95-106: Verify handling of 'childrenField' in 'transformData' function

In the transformData function, if childrenField is an empty string, the condition childrenField && item[childrenField] may not function as intended. This could lead to incorrect data processing or errors when transforming nested options.

Please ensure that the function correctly handles scenarios where childrenField might be an empty string, or consider enforcing a default value for childrenField to prevent potential issues.


116-118: Approved: Dynamic binding of model and options properties

The use of props.modelPropName and props.optionsPropName in the bindProps computed property allows for flexibility in component integration. This dynamic binding ensures compatibility with various component wrappers.


61-62: ⚠️ Potential issue

Critical Issue: Default 'childrenField' value may cause unexpected behavior

Setting childrenField to an empty string by default can lead to unintended behavior when processing nested options in the transformData function. When childrenField is an empty string, accessing item[childrenField] becomes item[''], which may not yield the expected results.

It's recommended to set a sensible default value, such as 'children', or modify the transformData function to handle an empty childrenField appropriately.

Suggested fix:

-  childrenField: '',
+  childrenField: 'children',
playground/src/adapter/component/index.ts (3)

52-52: Approved: Addition of 'ApiTreeSelect' to ComponentType

Including 'ApiTreeSelect' in the ComponentType union type extends the adaptability of the component system and aligns with the PR objectives.


92-94: Approved: Renaming 'modelField' to 'modelPropName'

The change from modelField to modelPropName improves consistency and clarity in property naming across components.


99-108: Approved: Implementation of 'ApiTreeSelect' component

The addition of the ApiTreeSelect component using ApiSelect with the TreeSelect component is well-structured and aligns with the enhancement goals of the PR.

apps/web-ele/src/adapter/component/index.ts (2)

81-82: Verify the 'visibleEvent' property for 'ElSelectV2'

The visibleEvent is set to 'onVisibleChange' for ApiSelect. Please confirm that ElSelectV2 emits an event named 'onVisibleChange', as event names might differ between components or versions.

Ensure that the event name matches the actual event emitted by ElSelectV2 to prevent any unexpected behavior.


87-97: Approved: Addition of 'ApiTreeSelect' component

The implementation of ApiTreeSelect using ApiSelect with ElTreeSelect and the specified properties is appropriate and enhances the component's capabilities.


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 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
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 and nitpick comments (5)
apps/web-naive/src/views/demos/form/basic.vue (1)

30-34: Refine TypeScript typing in afterFetch function

In the afterFetch function, the parameter item is currently typed as any. Since data is of type { name: string; path: string }[], it would be beneficial to specify the type of item for better type safety and IntelliSense support.

Suggested change:

- return data.map((item: any) => ({
+ return data.map((item: { name: string; path: string }) => ({
    label: item.name,
    value: item.path,
}))
apps/web-ele/src/views/demos/form/basic.vue (3)

31-36: Improve type safety in the afterFetch transformer

The current implementation uses any type which reduces type safety. Consider using a proper interface for the menu data structure.

-        afterFetch: (data: { name: string; path: string }[]) => {
-          return data.map((item: any) => ({
+        afterFetch: (data: Array<{ name: string; path: string }>) => {
+          return data.map((item) => ({
             label: item.name,
             value: item.path,
           }));
         },

46-62: Add JSDoc comments for the ApiTreeSelect configuration

The field mappings are crucial for the tree structure. Consider adding documentation to explain the expected data structure and field mappings.

     {
+      /**
+       * @description Tree select component that maps API data to a hierarchical structure
+       * @field childrenField - Field name for nested items (default: 'children')
+       * @field labelField - Field name for display text (default: 'name')
+       * @field valueField - Field name for selection value (default: 'path')
+       */
       component: 'ApiTreeSelect',
       componentProps: {
         api: getAllMenusApi,

Line range hint 171-183: Update setFormValues to include new API-based fields

The setFormValues function should be updated to include initial values for the new api and apiTree fields for consistency.

   function setFormValues() {
     formApi.setValues({
+      api: null, // or default value
+      apiTree: null, // or default value
       string: 'string',
       number: 123,
       radio: 'B',
playground/src/views/examples/form/basic.vue (1)

65-81: LGTM! Consider adding validation and type safety.

The ApiTreeSelect implementation follows good practices and integrates well with the existing form structure. A few suggestions for enhancement:

  1. Consider adding validation rules for required/optional status
  2. Add TypeScript interface for the API response structure
  3. Consider handling loading states for better UX

Example enhancement:

 {
   component: 'ApiTreeSelect',
   componentProps: {
     api: getAllMenusApi,
     childrenField: 'children',
     labelField: 'name',
     placeholder: '请选择',
     valueField: 'path',
+    // Add loading state handling
+    fieldNames: {
+      label: 'name',
+      value: 'path',
+      children: 'children'
+    },
   },
   fieldName: 'apiTree',
   label: 'ApiTreeSelect',
+  // Add validation rules
+  rules: [{ required: true, message: '请选择选项' }],
 },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 305549e and 7929a52.

📒 Files selected for processing (8)
  • apps/web-antd/src/adapter/component/index.ts (2 hunks)
  • apps/web-ele/src/adapter/component/index.ts (2 hunks)
  • apps/web-ele/src/views/demos/form/basic.vue (2 hunks)
  • apps/web-naive/src/adapter/component/index.ts (2 hunks)
  • apps/web-naive/src/views/demos/form/basic.vue (2 hunks)
  • packages/effects/common-ui/src/components/api-select/api-select.vue (3 hunks)
  • playground/src/adapter/component/index.ts (2 hunks)
  • playground/src/views/examples/form/basic.vue (1 hunks)
🔇 Additional comments (6)
playground/src/adapter/component/index.ts (1)

98-113: Verify compatibility of fieldNames with ApiSelect component

In the ApiTreeSelect implementation, the fieldNames prop is provided. Please ensure that the ApiSelect component accepts and properly handles the fieldNames prop when used with TreeSelect. This is to guarantee that the label, value, and children fields are correctly mapped, and the nested data structures function as intended.

apps/web-antd/src/adapter/component/index.ts (1)

97-112: ⚠️ Potential issue

Confirm event handler name for dropdown visibility

In the ApiTreeSelect component, the visibleEvent is set to 'onVisibleChange', whereas in the ApiSelect component for Ant Design Vue, the correct event for dropdown visibility might be 'onDropdownVisibleChange'. Please verify that the event name matches the actual event emitted by the TreeSelect component to ensure that data fetching is triggered appropriately when the dropdown is opened.

Suggested change:

- visibleEvent: 'onVisibleChange',
+ visibleEvent: 'onDropdownVisibleChange',
apps/web-naive/src/adapter/component/index.ts (1)

83-99: LGTM! Clean implementation of ApiTreeSelect adapter

The implementation correctly maps the ApiSelect component to Naive UI's TreeSelect with appropriate prop mappings and event handling.

apps/web-ele/src/adapter/component/index.ts (2)

86-99: LGTM! Well-structured ApiTreeSelect adapter

The implementation correctly maps to Element Plus's TreeSelect component with appropriate prop mappings for label, children, and model value.


81-85: Verify the visibleEvent change impact

The change from 'onDropdownVisibleChange' to 'onVisibleChange' affects the ApiSelect component. Ensure this change is compatible with Element Plus's latest API.

✅ Verification successful

Let's examine the specific usage of these events across different adapters to understand the implementation patterns.


Let's verify the Element Plus API documentation to confirm the correct event name.


Based on the analysis of the codebase, I can now provide the final response:

The visibleEvent change is consistent with UI framework patterns

The change to 'onVisibleChange' in Element Plus adapter aligns with the event naming patterns across other UI framework adapters:

  • Naive UI uses 'onVisibleChange'
  • Element Plus uses 'onVisibleChange'
  • Only Ant Design has a different pattern using 'onDropdownVisibleChange' for Select but 'onVisibleChange' for TreeSelect

The change maintains consistency with Element Plus's component event naming conventions and other framework adapters.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any other usages of onDropdownVisibleChange or onVisibleChange
rg -l "onDropdownVisibleChange|onVisibleChange" --type ts

Length of output: 236


Script:

#!/bin/bash
# Check the context of these event usages across adapters
rg "onDropdownVisibleChange|onVisibleChange" --type ts -C 5

Length of output: 5448


Script:

#!/bin/bash
# Search for the Element Plus component definition to verify the event name
rg "ElSelectV2" --type ts -C 5

Length of output: 1380

playground/src/views/examples/form/basic.vue (1)

69-76: Verify API response structure compatibility

The component uses the same API (getAllMenusApi) as ApiSelect but with different field mappings. Let's verify the API response structure matches both use cases.

✅ Verification successful

Let me analyze the results:

  1. The getAllMenusApi is consistently used across multiple applications (playground, web-naive, web-ele, web-antd) and returns RouteRecordStringComponent[] type.

  2. The field mappings in the form component:

    • childrenField: 'children'
    • labelField: 'name'
    • valueField: 'path'
  3. The ApiSelect component (in packages/effects/common-ui/src/components/api-select/api-select.vue) has default mappings:

    • labelField: 'label'
    • valueField: 'value'
    • childrenField: ''
  4. However, these default mappings can be overridden through props, and the component properly handles custom field mappings through the transformData function.

Let me generate the final response:

Field mappings are correctly configured

The component's field mappings (name, path, children) are compatible with the API response structure. While ApiSelect has different default mappings, it's designed to handle custom field names through props, which are properly transformed in its implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify API usage consistency and response structure

# Search for getAllMenusApi usage patterns
echo "Searching for getAllMenusApi usage patterns..."
rg -A 5 "getAllMenusApi" 

# Search for field name usage consistency
echo "Searching for field name patterns..."
rg -A 2 "labelField|valueField|childrenField"

Length of output: 13010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

FEATURE: 基于ant design vue 新增ApiTreeSelect组件
2 participants