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

refactor: ApiComponent with docs #5099

Merged
merged 4 commits into from
Dec 11, 2024
Merged

Conversation

mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Dec 11, 2024

Description

ApiSelect 改为 ApiComponent,不只是Select组件,ApiComponent也可以包装其它类似组件,为其提供获取远程选项数据的能力。

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 ApiComponent, replacing the previous ApiSelect, enhancing component registration and usage.
    • Added new documentation for the ApiComponent, including usage examples and detailed properties.
    • Expanded sidebar navigation to include the ApiComponent documentation.
  • Bug Fixes

    • Updated component imports to ensure proper functionality after renaming from ApiSelect to ApiComponent.
  • Chores

    • Removed the export of the obsolete ApiSelect component.
    • Adjusted exports to reflect the new ApiComponent in various modules.

@mynetfan mynetfan requested review from anncwb, vince292007 and a team as code owners December 11, 2024 02:31
Copy link

changeset-bot bot commented Dec 11, 2024

⚠️ No Changeset found

Latest commit: 47d57e3

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 11, 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 changes in this pull request involve the renaming and replacement of the ApiSelect component with ApiComponent across multiple files in the codebase. This includes updates to import statements, component registration, and documentation. Additionally, a new sidebar entry for the ApiComponent has been added to the documentation, along with a new markdown file detailing its usage. The overall functionality and structure of the components remain unchanged, ensuring that existing features continue to operate as intended.

Changes

File Path Change Summary
apps/web-antd/src/adapter/component/index.ts Replaced ApiSelect with ApiComponent in imports and usage within initComponentAdapter.
apps/web-ele/src/adapter/component/index.ts Replaced ApiSelect with ApiComponent in imports and usage within initComponentAdapter.
apps/web-naive/src/adapter/component/index.ts Replaced ApiSelect with ApiComponent in imports and usage within initComponentAdapter.
docs/.vitepress/config/zh.mts Added new sidebar item for ApiComponent linking to common-ui/vben-api-component.
docs/src/components/common-ui/vben-api-component.md Added documentation for ApiComponent, detailing its usage and properties.
docs/src/demos/vben-api-component/cascader/index.vue Introduced new Vue component using ApiComponent with hierarchical data structure.
packages/effects/common-ui/src/components/api-component/api-component.vue Updated type declarations, renamed component from ApiSelect to ApiComponent.
packages/effects/common-ui/src/components/api-component/index.ts Added export statement for ApiComponent.
packages/effects/common-ui/src/components/api-select/index.ts Deleted file exporting ApiSelect.
packages/effects/common-ui/src/components/index.ts Updated export from api-select to api-component.
playground/src/adapter/component/index.ts Replaced ApiSelect with ApiComponent in imports and usage within initComponentAdapter.

Possibly related PRs

Suggested labels

documentation

Suggested reviewers

  • vince292007
  • anncwb

Poem

🐰 In the garden of code, changes bloom,
ApiComponent now takes up the room.
With a hop and a skip, the imports align,
Documentation shines, all is divine!
Components now dance, in a new light,
Hooray for the changes, everything's bright! 🌼


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. (Experiment)
  • @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.

@mynetfan mynetfan force-pushed the refactor/api-component branch from 47d57e3 to 1a170c2 Compare December 11, 2024 02:31
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

🧹 Outside diff range and nitpick comments (10)
docs/src/demos/vben-api-component/cascader/index.vue (1)

83-89: Consider enhancing the mock API implementation

The mock API implementation is functional but could benefit from error handling and loading state simulation.

Consider this enhanced implementation:

 function fetchApi(): Promise<Record<string, any>> {
   return new Promise((resolve) => {
     setTimeout(() => {
+      // Simulate API success rate
+      if (Math.random() > 0.9) {
+        throw new Error('Simulated API failure');
+      }
       resolve(treeData);
     }, 1000);
   });
 }
playground/src/adapter/component/index.ts (1)

Line range hint 86-95: Verify ApiComponent configuration consistency

The ApiSelect implementation uses onVisibleChange while the demo uses onDropdownVisibleChange. This inconsistency might cause issues.

Apply this fix:

         ApiComponent,
         {
           placeholder: $t('ui.placeholder.select'),
           ...props,
           ...attrs,
           component: Select,
           loadingSlot: 'suffixIcon',
           modelPropName: 'value',
-          visibleEvent: 'onVisibleChange',
+          visibleEvent: 'onDropdownVisibleChange',
         },
docs/src/components/common-ui/vben-api-component.md (3)

148-149: Remove empty code fence block.

The empty code fence block at the end of the file should be removed as it serves no purpose.

-```
-
-```
🧰 Tools
🪛 Markdownlint (0.35.0)

148-148: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)


136-136: Enhance childrenField prop description.

The description for childrenField prop shows an empty default value. Consider adding more context about when this field should be used and its importance in hierarchical data structures.

-| childrenField | 子级数据字段名,需要层级数据的组件可用 | `string` | `` |
+| childrenField | 子级数据字段名,用于树形结构数据(如TreeSelect、Cascader等)中指定子节点的字段名 | `string` | `` |

21-122: Enhance example code documentation.

While the example demonstrates Cascader integration well, it could benefit from additional comments explaining key configuration options and data structure requirements.

Add explanatory comments for key props:

 <template>
   <ApiComponent
     :api="fetchApi"
     :component="Cascader"
+    <!-- Disable immediate loading to fetch data only when dropdown opens -->
     :immediate="false"
+    <!-- Specify the field name for nested children in the tree structure -->
     children-field="children"
+    <!-- Configure loading indicator to appear in the suffix icon position -->
     loading-slot="suffixIcon"
+    <!-- Event that triggers data fetching when dropdown visibility changes -->
     visible-event="onDropdownVisibleChange"
   />
 </template>
apps/web-naive/src/adapter/component/index.ts (1)

Based on the search results from the previous commands, I can now provide a final response:

TreeSelect prop mappings need adjustment for Naive UI

The current configuration appears to mix prop names from different UI frameworks. For Naive UI's TreeSelect:

  • nodeKey and keyField are redundant - Naive UI uses only keyField for unique node identification
  • loadingSlot should be 'arrow' as correctly set (verified from other adapter implementations)
🔗 Analysis chain

Line range hint 86-97: Verify TreeSelect specific prop mappings.

The TreeSelect configuration includes additional props specific to tree structures. Please verify that these prop names match Naive UI's TreeSelect component API:

  • nodeKey
  • keyField
  • loadingSlot

Let me gather more information about NTreeSelect's API specifically.


Let me try a different approach to find TreeSelect related information.


Let me try one more search to find Naive UI's TreeSelect documentation or type definitions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for TreeSelect usage in the codebase to verify prop names
rg -A 5 "NTreeSelect.*nodeKey|keyField|loadingSlot"

Length of output: 5219


Script:

#!/bin/bash
# Search for NTreeSelect documentation or type definitions
rg -A 10 "NTreeSelect|TreeSelect.*props" --type typescript

Length of output: 95


Script:

#!/bin/bash
# Search for TreeSelect related files and their content
rg -A 10 "TreeSelect" 

Length of output: 29556


Script:

#!/bin/bash
# Search for NTreeSelect props or documentation
rg "NTreeSelect.*props|interface.*TreeSelect" -A 5

Length of output: 52

packages/effects/common-ui/src/components/api-component/api-component.vue (1)

Line range hint 133-146: Enhance error handling in fetchApi function.

The current error handling only logs to console and resets the loading state. Consider adding error state management and error event emission.

 } catch (error) {
   console.warn(error);
   // reset status
   isFirstLoaded.value = false;
+  emit('error', error);
+  refOptions.value = props.options || [];
 }

Also, consider adding error event to the emits definition:

 const emit = defineEmits<{
   optionsChange: [OptionsItem[]];
+  error: [Error];
 }>();
apps/web-ele/src/adapter/component/index.ts (2)

12-12: Consider updating ComponentType to reflect the new ApiComponent architecture

While the implementation has been updated to use ApiComponent, the ComponentType still lists 'ApiSelect' and 'ApiTreeSelect' as separate types. Consider adding 'ApiComponent' to maintain consistency with the new architecture.

export type ComponentType =
+ | 'ApiComponent'
  | 'ApiSelect'
  | 'ApiTreeSelect'
  | 'Checkbox'
  // ... rest of the types

Also applies to: 32-52


Line range hint 73-97: Consider extracting common ApiComponent configuration

Both ApiSelect and ApiTreeSelect share similar configuration. Consider extracting the common props to reduce duplication:

+const commonApiProps = {
+  placeholder: $t('ui.placeholder.select'),
+  loadingSlot: 'loading',
+  visibleEvent: 'onVisibleChange',
+};

 ApiSelect: (props, { attrs, slots }) => {
   return h(
     ApiComponent,
     {
-      placeholder: $t('ui.placeholder.select'),
+      ...commonApiProps,
       ...props,
       ...attrs,
       component: ElSelectV2,
-      loadingSlot: 'loading',
-      visibleEvent: 'onVisibleChange',
     },
     slots,
   );
 },
docs/.vitepress/config/zh.mts (1)

165-168: LGTM: Documentation structure is well-organized

The ApiComponent documentation is properly integrated into the sidebar under the Common Components section. Consider adding a brief description in the sidebar text to better indicate its wrapper functionality.

 {
   link: 'common-ui/vben-api-component',
-  text: 'ApiComponent Api组件包装器',
+  text: 'ApiComponent 通用API数据加载组件包装器',
 },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2cc918f and 1a170c2.

📒 Files selected for processing (11)
  • apps/web-antd/src/adapter/component/index.ts (3 hunks)
  • apps/web-ele/src/adapter/component/index.ts (3 hunks)
  • apps/web-naive/src/adapter/component/index.ts (3 hunks)
  • docs/.vitepress/config/zh.mts (1 hunks)
  • docs/src/components/common-ui/vben-api-component.md (1 hunks)
  • docs/src/demos/vben-api-component/cascader/index.vue (1 hunks)
  • packages/effects/common-ui/src/components/api-component/api-component.vue (3 hunks)
  • packages/effects/common-ui/src/components/api-component/index.ts (1 hunks)
  • packages/effects/common-ui/src/components/api-select/index.ts (0 hunks)
  • packages/effects/common-ui/src/components/index.ts (1 hunks)
  • playground/src/adapter/component/index.ts (3 hunks)
💤 Files with no reviewable changes (1)
  • packages/effects/common-ui/src/components/api-select/index.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/effects/common-ui/src/components/index.ts
  • packages/effects/common-ui/src/components/api-component/index.ts
🧰 Additional context used
🪛 Markdownlint (0.35.0)
docs/src/components/common-ui/vben-api-component.md

148-148: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (8)
docs/src/demos/vben-api-component/cascader/index.vue (1)

92-99: LGTM! Well-configured ApiComponent integration

The ApiComponent is properly configured with Cascader, demonstrating key features:

  • Lazy loading through immediate: false
  • Correct field mapping with children-field
  • Loading state handling via loading-slot
  • Proper event handling with visible-event
playground/src/adapter/component/index.ts (1)

Line range hint 101-112: Consider standardizing field name configurations

The ApiTreeSelect implementation explicitly defines fieldNames while the base Select doesn't. Consider standardizing this approach across all select-like components.

Let's verify if other select-like components need similar field mappings:

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

Line range hint 85-94: Fix visibleEvent prop for consistency

The same inconsistency with visibleEvent exists in this implementation.

Apply the same fix as suggested for the playground adapter:

         ApiComponent,
         {
           placeholder: $t('ui.placeholder.select'),
           ...props,
           ...attrs,
           component: Select,
           loadingSlot: 'suffixIcon',
           modelPropName: 'value',
-          visibleEvent: 'onVisibleChange',
+          visibleEvent: 'onDropdownVisibleChange',
         },

Line range hint 100-111: Standardize field name configurations across components

The same consideration about standardizing fieldNames configuration applies here. Consider applying consistent field mapping across all select-like components.

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

Line range hint 73-82: LGTM! Prop mappings for ApiSelect look correct.

The component registration properly maps the NSelect component with correct prop names:

  • modelPropName: 'value' matches Naive UI's API
  • Default placeholder is correctly set
packages/effects/common-ui/src/components/api-component/api-component.vue (2)

21-21: LGTM! Type change from VNode to Component is correct.

The type change improves type safety and better represents the component's purpose.


56-56: LGTM! Component name updated correctly.

The component name has been updated to reflect its more generic purpose.

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

Line range hint 191-193: LGTM: Component registration is properly handled

The component registration to globalShareState is correctly implemented and maintains backward compatibility.

@mynetfan mynetfan merged commit eec6f41 into vbenjs:main Dec 11, 2024
14 checks passed
@mynetfan mynetfan deleted the refactor/api-component branch December 11, 2024 02:45
@anncwb anncwb added the enhancement New feature or request label Dec 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants