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: add api-select component #5024

Merged
merged 1 commit into from
Dec 4, 2024
Merged

feat: add api-select component #5024

merged 1 commit into from
Dec 4, 2024

Conversation

anncwb
Copy link
Collaborator

@anncwb anncwb commented Dec 4, 2024

Description

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

Release Notes

  • New Features

    • Introduced the ApiSelect component for dynamic option selection from an API.
    • Enhanced forms with the new ApiSelect field for fetching and displaying menu options.
  • Updates

    • Updated component registration to include ApiSelect across various adapters.
    • Added new utility functions from the lodash library to enhance data handling.
  • Dependencies

    • Updated multiple dependencies to their latest versions for improved performance and compatibility.

@anncwb anncwb added the feature label Dec 4, 2024
@anncwb anncwb requested review from vince292007 and a team as code owners December 4, 2024 14:50
Copy link

changeset-bot bot commented Dec 4, 2024

⚠️ No Changeset found

Latest commit: b665734

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 4, 2024

Walkthrough

The changes in this pull request introduce the ApiSelect component across multiple applications and packages, enhancing the component library with new functionalities. The ApiSelect component is integrated into the component adapters, allowing it to be recognized and utilized in various forms. Additionally, several dependencies related to the lodash library are added, and various package versions are updated to maintain compatibility and incorporate improvements.

Changes

File Path Change Summary
apps/web-antd/src/adapter/component/index.ts Added ApiSelect to imports and updated ComponentType. Introduced ApiSelect function in initComponentAdapter.
apps/web-ele/src/adapter/component/index.ts Added ApiSelect to imports and updated ComponentType. Defined custom rendering for ApiSelect in initComponentAdapter.
apps/web-naive/src/adapter/component/index.ts Added ApiSelect to imports and updated ComponentType. Integrated ApiSelect into the global component state.
packages/@core/base/shared/package.json Added dependencies lodash.get and lodash.isequal, updated type definitions. Adjusted export paths in exports.
packages/@core/base/shared/src/utils/index.ts Added exports for get and isEqual from lodash.
packages/effects/common-ui/src/components/api-select/api-select.vue Introduced ApiSelect component with props for API fetching and option handling.
packages/effects/common-ui/src/components/api-select/index.ts Added export for ApiSelect from api-select.vue.
packages/effects/common-ui/src/components/index.ts Added export for all components from api-select.
playground/src/adapter/component/index.ts Added ApiSelect to imports and updated ComponentType. Defined ApiSelect function in initComponentAdapter.
playground/src/views/examples/form/basic.vue Added ApiSelect field in BaseForm schema to fetch options from an API.
pnpm-workspace.yaml Updated versions for multiple dependencies to maintain compatibility and incorporate fixes.

Possibly related issues

Possibly related PRs

Suggested reviewers

  • vince292007

🐇 "In the meadow where we play,
New components come out to stay.
ApiSelect hops in with glee,
Fetching options, oh so free!
With props and slots, it’s quite a treat,
Building forms that can’t be beat!" 🐇

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)


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

🧹 Outside diff range and nitpick comments (6)
packages/effects/common-ui/src/components/api-select/api-select.vue (3)

133-135: Enhance error handling by providing user feedback

Currently, when an error occurs during the API fetch, it is only logged to the console. Consider notifying the user or emitting an error event to improve the user experience.

Apply this diff to emit an error event:

 try {
   loading.value = true;
   // fetch logic...
 } catch (error) {
   console.warn(error);
+  emit('error', error);
   // reset status
   isFirstLoaded.value = false;
 } finally {

174-176: Use descriptive variable names in template loops

In the v-for loop over $slots, consider using a more descriptive variable name than item, such as slotName, to enhance code readability.

Apply this diff to rename the variable:

-<template v-for="item in Object.keys($slots)" #[item]="data">
-  <slot :name="item" v-bind="data || {}"></slot>
+</template v-for="slotName in Object.keys($slots)" #[slotName]="data">
+  <slot :name="slotName" v-bind="data || {}"></slot>
 </template>

81-85: Optimize option processing by using map function

Consider using the Array.prototype.map method to transform refOptionsData, which can make the code more concise and readable.

Apply this diff for the refactor:

 const getOptions = computed(() => {
   const { labelField, valueField, numberToString } = props;

-  const data: OptionsItem[] = [];
-  const refOptionsData = unref(refOptions);
-
-  for (const next of refOptionsData) {
-    if (next) {
-      const value = get(next, valueField);
-      data.push({
-        ...objectOmit(next, [labelField, valueField]),
-        label: get(next, labelField),
-        value: numberToString ? `${value}` : value,
-      });
-    }
-  }
+  const refOptionsData = unref(refOptions);
+  const data = refOptionsData
+    .filter(next => next)
+    .map(next => {
+      const value = get(next, valueField);
+      return {
+        ...objectOmit(next, [labelField, valueField]),
+        label: get(next, labelField),
+        value: numberToString ? `${value}` : value,
+      };
+    });

   return data.length > 0 ? data : props.options;
 });
packages/@core/base/shared/src/utils/index.ts (1)

18-19: Verify the necessity of new lodash dependencies

Adding get and isEqual from lodash increases the bundle size. Consider using native JavaScript equivalents or existing utility functions to achieve the same functionality.

If lodash functions are necessary, ensure that they are used optimally. Alternatively, you can use:

  • For get: Use optional chaining and nullish coalescing operators.
  • For isEqual: Use JSON.stringify(a) === JSON.stringify(b) for simple objects.
apps/web-naive/src/adapter/component/index.ts (1)

45-45: Update ComponentType definition documentation

Add comments or documentation to the ComponentType type to reflect the addition of ApiSelect, enhancing code readability and maintainability.

Apply this diff to add a comment:

 export type ComponentType =
+  // Added ApiSelect component for asynchronous option loading
   | 'ApiSelect'
   | 'Checkbox'
   | 'CheckboxGroup'
playground/src/adapter/component/index.ts (1)

83-96: Consider adding error handling for the Select component

The implementation looks correct for Ant Design Vue, but consider adding error handling for cases where the Select component fails to load or render.

 ApiSelect: (props, { attrs, slots }) => {
+  try {
     return h(
       ApiSelect,
       {
         ...props,
         ...attrs,
         component: Select,
         loadingSlot: 'suffixIcon',
         modelField: 'value',
         visibleEvent: 'onVisibleChange',
       },
       slots,
     );
+  } catch (error) {
+    console.error('Failed to render ApiSelect:', error);
+    return null;
+  }
 },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 845f2a2 and b665734.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • apps/web-antd/src/adapter/component/index.ts (3 hunks)
  • apps/web-ele/src/adapter/component/index.ts (4 hunks)
  • apps/web-naive/src/adapter/component/index.ts (3 hunks)
  • packages/@core/base/shared/package.json (1 hunks)
  • packages/@core/base/shared/src/utils/index.ts (1 hunks)
  • packages/effects/common-ui/src/components/api-select/api-select.vue (1 hunks)
  • packages/effects/common-ui/src/components/api-select/index.ts (1 hunks)
  • packages/effects/common-ui/src/components/index.ts (1 hunks)
  • playground/src/adapter/component/index.ts (3 hunks)
  • playground/src/views/examples/form/basic.vue (2 hunks)
  • pnpm-workspace.yaml (9 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/effects/common-ui/src/components/api-select/index.ts
🔇 Additional comments (9)
packages/effects/common-ui/src/components/api-select/api-select.vue (1)

94-97: Ensure proper synchronization of model values

When updating the model value, ensure that the change is properly synced with the parent component, especially when using dynamic model fields.

Run the following script to check for correct usage of defineModel and model updates:

✅ Verification successful

Model value synchronization is correctly implemented

The code implements proper model value synchronization:

  • Uses defineModel() to create a two-way binding
  • Correctly updates the model value through the dynamic onUpdate:${props.modelField} handler
  • Properly binds the model value to the child component through computed bindProps
  • Handles both default modelValue and custom model field names via props.modelField
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that model updates are correctly implemented.

# Test: Search for incorrect usage of model updates.
ast-grep 'defineModel($$_)' --lang ts
ast-grep 'modelValue.value = $_' --lang ts

Length of output: 337


Script:

#!/bin/bash
# Let's try a different approach to verify model updates in Vue components

# Search for model update patterns in Vue files
rg -U "onUpdate:.*modelValue\.value.*=.*" --type vue -A 2 -B 2

# Search for defineModel usage in Vue files
rg "defineModel" --type vue -A 2 -B 2

# Look for v-model usage in the component
rg "v-model" --type vue -A 2 -B 2

# Check the entire api-select component implementation
fd "api-select.vue" --type f --exec cat {}

Length of output: 4558

packages/effects/common-ui/src/components/index.ts (1)

Line range hint 1-9: Confirm export order and potential conflicts

Ensure that exporting all from './api-select' at the top does not cause any conflicts with other exports in this file or lead to unintended side effects.

Run the following script to check for export conflicts:

✅ Verification successful

Based on the output from the shell scripts, I can now generate the final response:

No export conflicts found in the component exports

The exports in packages/effects/common-ui/src/components/index.ts are safe and do not cause any conflicts because:

  1. Each module is exported using wildcard exports (export *) from distinct paths
  2. The named exports from @vben-core/shadcn-ui are explicitly listed and don't overlap with other exports
  3. The final export globalShareState is a named export from a different module

The export order is also appropriate, with local component exports listed first, followed by external module exports.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for duplicate exports and verify export order.

# Test: Find duplicate export names.
ast-grep 'export { $$$_ } from $_' --lang ts
ast-grep 'export * from $_' --lang ts

Length of output: 341


Script:

#!/bin/bash
# Let's check the content of each exported module to understand potential conflicts
# First, let's check if the files exist and their content
fd -e ts "api-select|captcha|ellipsis-text|icon-picker|page|resize" -x cat {}

# Also check the content of the index.ts file
cat packages/effects/common-ui/src/components/index.ts

# Check if there are any re-exports of similar names across these files
rg "export.*as" -A 1 -B 1

Length of output: 65822

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

68-79: Ensure consistent component integration for ApiSelect

Verify that the ApiSelect component integration aligns with how other components are handled in the adapter. Ensure that props and events are correctly mapped.

Run the following script to check for consistent component handling:

✅ Verification successful

The previous ast-grep pattern had syntax issues. Let's try with a corrected pattern and also use ripgrep as a backup to find similar component integrations. This will help us verify if the ApiSelect integration follows the same pattern as other components in the codebase.


Let's try a broader search to find component integrations and also locate the relevant component adapter files. This will help us understand the component integration patterns across the codebase.


The ApiSelect component integration is consistent across UI frameworks

The implementation in apps/web-naive/src/adapter/component/index.ts follows the same pattern used in other UI framework adapters (Antd, Element Plus). All implementations:

  • Use the same component wrapper structure with h(ApiSelect, {...})
  • Pass through props and attrs consistently
  • Configure the appropriate framework-specific select component
  • Set framework-specific properties (e.g., modelField: 'value' for Naive UI)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all components follow the same integration pattern.

# Test: Search for component integrations.
ast-grep '$_: (props, { $$ }) => { $$$ }' --lang ts

Length of output: 191


Script:

#!/bin/bash
# Search for component integrations with a corrected ast-grep pattern
ast-grep --pattern '$_: ($_, { $$ }) => { return h($$$) }'

# Also search for similar component definitions using ripgrep
rg "return h\(" -A 3 "component.*\.ts$"

Length of output: 159


Script:

#!/bin/bash
# Search for component integrations using ripgrep without file pattern restriction
rg "return h\(" -A 3

# Find all potential component adapter files
fd "component.*\.ts"

# Search specifically for ApiSelect usage
rg "ApiSelect" -A 5 -B 5

Length of output: 22432

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

11-11: LGTM: Imports are correctly organized

The imports are properly organized with the new ApiSelect component from @vben/common-ui and ElSelectV2 from element-plus.

Also applies to: 25-25


45-45: LGTM: ComponentType definition is properly updated

The ApiSelect type is correctly added to the union type while maintaining alphabetical order.


67-79: 🛠️ Refactor suggestion

Verify the event name for dropdown visibility

The implementation looks correct, but there might be a discrepancy in the event name. Element Plus typically uses visible-change instead of onDropdownVisibleChange.

Consider updating the event name:

-  visibleEvent: 'onDropdownVisibleChange',
+  visibleEvent: 'visible-change',
pnpm-workspace.yaml (2)

16-16: Review version pinning strategy for dependencies

Several dependencies are using caret ranges (^). While this allows for minor version updates, it may lead to inconsistent builds across different environments. Consider:

  1. Using exact versions for critical dependencies
  2. Adding package-lock file to ensure consistent installations

Also applies to: 25-26, 39-39, 46-47, 53-54, 67-67, 85-85, 92-92, 107-107, 117-118, 119-119, 121-121, 135-135, 140-140, 156-156, 164-164, 172-173, 179-180


117-118: Verify lodash dependency usage

New lodash dependencies (lodash.get and lodash.isequal) have been added, likely to support the ApiSelect component. Ensure these utilities are used efficiently.

✅ Verification successful

Lodash utilities are used appropriately and efficiently

The verification shows that both lodash utilities are used efficiently:

  • lodash.get is used in the ApiSelect component for safe property access of nested objects
  • lodash.isEqual is used for deep equality comparison in ApiSelect's value change detection
  • Both utilities are centrally re-exported from @core/base/shared/src/utils/index.ts, promoting reusability
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check usage of lodash utilities

# Search for lodash.get usage
echo "Checking lodash.get usage:"
rg "lodash\.get|import.*from.*lodash\.get" -A 3

# Search for lodash.isequal usage
echo "Checking lodash.isequal usage:"
rg "lodash\.isEqual|import.*from.*lodash\.isequal" -A 3

Length of output: 2761


Script:

#!/bin/bash
# Let's check for actual usage of these lodash utilities in the codebase

# Search for imports and usage of get utility
echo "Searching for get utility usage:"
rg -g '*.{ts,tsx,js,jsx,vue}' "import.*get.*from.*lodash|import.*get.*from.*'@core/base/shared'|get\(" -A 2

# Search for imports and usage of isEqual utility
echo "Searching for isEqual utility usage:"
rg -g '*.{ts,tsx,js,jsx,vue}' "import.*isEqual.*from.*lodash|import.*isEqual.*from.*'@core/base/shared'|isEqual\(" -A 2

# Check if these are re-exported from other files
echo "Checking re-exports:"
rg -g '*.{ts,tsx,js,jsx,vue}' "export.*get.*from|export.*isEqual.*from" -A 2

Length of output: 5554

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

10-10: Verify API import path

Ensure that the API import path is correct and the API function is properly exported.

✅ Verification successful

API import path is correctly defined and exported

The getAllMenusApi function is properly exported from playground/src/api/core/menu.ts and the import path #/api appears to be an alias that resolves to the API directory. The function implementation is consistent across all variants and returns menu data from the /menu/all endpoint.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if getAllMenusApi is properly exported

# Search for getAllMenusApi definition
echo "Checking getAllMenusApi definition:"
rg "export.*getAllMenusApi" -A 3

# Search for potential circular dependencies
echo "Checking for circular dependencies:"
rg "import.*from.*api.*" --files-with-matches

Length of output: 3306

packages/@core/base/shared/package.json Show resolved Hide resolved
apps/web-antd/src/adapter/component/index.ts Show resolved Hide resolved
playground/src/views/examples/form/basic.vue Show resolved Hide resolved
playground/src/views/examples/form/basic.vue Show resolved Hide resolved
@anncwb anncwb merged commit 9896a67 into main Dec 4, 2024
14 checks passed
@anncwb anncwb deleted the feature/api-select branch December 4, 2024 14:56
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.

1 participant