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: form 表单-指定哦组建添加一个标准自定义插槽示例 #4887

Closed
wants to merge 2 commits into from

Conversation

GavinLucky
Copy link
Contributor

@GavinLucky GavinLucky commented Nov 13, 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

  • New Features

    • Introduced the GraphValidateCode component for handling graphical validation codes.
    • Added getBase64Img function to retrieve random base64-encoded images.
    • Enhanced form functionality with a new form instance and integrated GraphValidateCode component.
  • Bug Fixes

    • Updated field name in form schema for improved clarity.
  • Documentation

    • Improved comments and structure for better understanding of new components and functions.

Copy link

changeset-bot bot commented Nov 13, 2024

⚠️ No Changeset found

Latest commit: 84534d0

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 Nov 13, 2024

Walkthrough

This pull request introduces a new Vue component, GraphValidateCode, designed for graphical validation codes, utilizing TypeScript and the Vue Composition API. It includes an interface for props and manages image loading and validation states. Additionally, a new function for retrieving random base64 images is added, alongside modifications to an existing form component to integrate the new validation code functionality. These changes enhance the form's capabilities and user interaction through improved validation and image handling.

Changes

File Path Change Summary
playground/src/views/examples/form/costom-sub/graph-validate-code.vue - Added component GraphValidateCode
- Added interface IGraphValidateCodeProps
- Added method loadImgFn
playground/src/views/examples/form/costom-sub/img.data.ts - Added constant imgDataList
- Added function getBase64Img() for retrieving random base64 images
playground/src/views/examples/form/custom.vue - Imported getBase64Img and GraphValidateCode
- Added async function getImgApi
- Updated form field name from field3 to code
- Created new form instance FormCustom

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • vince292007
  • anncwb

🐇 In a world of codes and spins,
A rabbit hops where validation begins.
With images bright and inputs so neat,
Our GraphValidateCode can't be beat!
So click and load, let errors be few,
For every form, there's magic anew! ✨

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.

playground/src/views/examples/form/costom-sub/graph-validate-code.vue

Oops! Something went wrong! :(

ESLint: 9.14.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: 3

🧹 Outside diff range and nitpick comments (9)
playground/src/views/examples/form/costom-sub/graph-validate-code.vue (4)

25-31: Simplify computed property.

The validateFailedComputed can be simplified as it's just forwarding the prop value.

 const validateFailedComputed = computed(() => {
-  return !!props.propValidateFailed;
+  return props.validateFailed;
 });

58-72: Clean up event handlers and add proper typing.

  1. Remove debug comments
  2. Add proper type for change event
  3. Remove redundant comments
 const handleBlur = () => {
-  // console.log('handleBlur');
-  emit('onEmitOnBlur');
-  // 光标失焦
+  emit('blur');
 };
 const handleFocus = () => {
-  // console.log('handleFocus');
-  emit('onEmitOnFocus');
-  // 光标聚焦
+  emit('focus');
 };
-const handleChange = (e) => {
-  // console.log('handleChange', e);
-  emit('onEmitOnChange', e);
-  // 输入框内容改变
+const handleChange = (e: Event) => {
+  emit('change', e);
 };

73-82: Improve lifecycle handling and method exposure.

  1. The arbitrary 100ms delay in onMounted seems unnecessary
  2. The exposed method name could be more descriptive
 onMounted(() => {
-  setTimeout(() => {
-    loadImgDataApiFn();
-  }, 100);
+  loadImgDataApiFn();
 });
 defineExpose({
-  loadImgFn: () => {
+  reloadValidationImage: () => {
     return loadImgDataApiFn();
   },
 });

85-127: Enhance accessibility and user experience.

  1. Add meaningful alt text for the validation image
  2. Consider making dimensions configurable via props
  3. Add aria-labels for better accessibility
       <Input
         v-model:value="inputValue"
         :class="[
           validateFailedComputed ? 'border-destructive' : 'border-light',
         ]"
         placeholder="请输入验证码"
+        aria-label="验证码输入框"
         @blur="handleBlur"
         @change="handleChange"
         @focus="handleFocus"
       />
...
             <img
               :src="imgDataRef"
               :style="{
-                height: '28px',
+                height: props.imageHeight || '28px',
                 width: 'auto',
               }"
-              alt=""
+              alt="图形验证码"
+              aria-label="点击更新验证码"
               class="mx-auto h-full object-contain"
             />
playground/src/views/examples/form/custom.vue (4)

9-9: Fix typo in import paths

The folder name 'costom-sub' appears to be misspelled. It should be 'custom-sub'.

-import { getBase64Img } from '#/views/examples/form/costom-sub/img.data';
-import GraphValidateCode from './costom-sub/graph-validate-code.vue';
+import { getBase64Img } from '#/views/examples/form/custom-sub/img.data';
+import GraphValidateCode from './custom-sub/graph-validate-code.vue';

Also applies to: 11-11


13-19: Consider reducing artificial delay in getImgApi

The 500ms delay might negatively impact user experience. Consider:

  1. Reducing the delay if it's for testing purposes
  2. Removing it if it's not necessary for production
  3. Adding loading state handling if the delay is required
 const getImgApi = () => {
   return new Promise<string>((resolve) => {
-    setTimeout(() => {
-      resolve(getBase64Img());
-    }, 500);
+    resolve(getBase64Img());
   });
 };

62-104: Consider extracting common form configuration

Both Form and FormCustom share similar configuration. Consider extracting the common configuration to reduce duplication.

const commonFormConfig = {
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelClass: 'w-2/6',
  },
  layout: 'horizontal',
  handleSubmit: onSubmit,
  wrapperClass: 'grid-cols-1 md:grid-cols-2',
};

const [Form] = useVbenForm({
  ...commonFormConfig,
  schema: [/* ... */],
});

const [FormCustom] = useVbenForm({
  ...commonFormConfig,
  schema: [/* ... */],
});

126-134: Simplify event naming and handlers

The current implementation has some redundancies in event naming and an empty handler:

  1. The 'on-emit-on-' prefix is redundant
  2. The empty focus handler can be omitted
 <GraphValidateCode
   :prop-api="props.api"
   :prop-validate-failed="props.isInValid"
   :value="props.value"
-  @on-emit-on-blur="props.handleBlur()"
-  @on-emit-on-change="props.handleChange($event)"
-  @on-emit-on-focus="() => {}"
+  @blur="props.handleBlur"
+  @change="props.handleChange"
   @update:value="(nV) => props.setValue(nV)"
 />
playground/src/views/examples/form/costom-sub/img.data.ts (1)

1-7: Consider alternative approaches for storing and generating validation images.

The current implementation has several potential issues:

  1. Storing large base64 strings in source code reduces maintainability and increases bundle size
  2. A limited set of 5 hardcoded images makes the validation codes predictable and less secure

Consider these alternatives:

  1. Store images in separate files and load them dynamically
  2. Use a server-side API to generate random validation codes
  3. Use a client-side canvas to generate dynamic validation codes
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8cc73cf and e12b35c.

📒 Files selected for processing (3)
  • playground/src/views/examples/form/costom-sub/graph-validate-code.vue (1 hunks)
  • playground/src/views/examples/form/costom-sub/img.data.ts (1 hunks)
  • playground/src/views/examples/form/custom.vue (3 hunks)
🔇 Additional comments (3)
playground/src/views/examples/form/costom-sub/graph-validate-code.vue (1)

1-5: LGTM! Imports are clean and well-organized.

The component setup uses appropriate imports from Vue core and Ant Design Vue library.

playground/src/views/examples/form/custom.vue (2)

58-61: LGTM: Grid layout improvements

The grid layout modifications provide better responsiveness with appropriate breakpoints.


123-137: Verify implementation matches PR objectives

The implementation adds a custom slot example for the form component as intended in the PR title "feat: form 表单-指定哦组建添加一个标准自定义插槽示例". However, let's verify that this is the standard approach for custom slots in the project.

✅ Verification successful

Custom slot implementation aligns with PR objectives

Verified that playground/src/views/examples/form/custom.vue correctly implements the standard custom slot as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar custom slot implementations in the codebase
rg -l "template\s+#\w+=\"props\"" --type vue

Length of output: 72


Script:

#!/bin/bash
# Search for similar custom slot implementations in .vue files
rg -l "template\s+#\w+=\"props\"" --glob '*.vue'

Length of output: 94

Comment on lines 8 to 23
defineOptions({
name: 'GraphValidateCode',
});
interface IGraphValidateCodeProps {
/** 获取图片Api接口 */
propApi?: () => Promise<string>;
/** 校验失败状态 */
propValidateFailed: boolean;
}
// eslint-disable-next-line vue/define-macros-order
const props = defineProps<IGraphValidateCodeProps>();
const emit = defineEmits<{
(e: 'onEmitOnBlur'): void;
(e: 'onEmitOnChange'): void;
(e: 'onEmitOnFocus'): void;
}>();
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

Improve naming conventions and documentation.

  1. Event names should follow Vue's conventions:

    • Remove redundant 'onEmit' prefix
    • Use kebab-case for event names
  2. Props could be more concise:

    • propApiapi
    • propValidateFailedvalidateFailed
  3. Add JSDoc for emitted events

Apply these changes:

 interface IGraphValidateCodeProps {
   /** 获取图片Api接口 */
-  propApi?: () => Promise<string>;
+  api?: () => Promise<string>;
   /** 校验失败状态 */
-  propValidateFailed: boolean;
+  validateFailed: boolean;
 }
 const props = defineProps<IGraphValidateCodeProps>();
+/** @event {() => void} blur - Emitted when input loses focus */
+/** @event {() => void} change - Emitted when input value changes */
+/** @event {() => void} focus - Emitted when input gains focus */
 const emit = defineEmits<{
-  (e: 'onEmitOnBlur'): void;
-  (e: 'onEmitOnChange'): void;
-  (e: 'onEmitOnFocus'): void;
+  (e: 'blur'): void;
+  (e: 'change'): void;
+  (e: 'focus'): void;
 }>();
📝 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
defineOptions({
name: 'GraphValidateCode',
});
interface IGraphValidateCodeProps {
/** 获取图片Api接口 */
propApi?: () => Promise<string>;
/** 校验失败状态 */
propValidateFailed: boolean;
}
// eslint-disable-next-line vue/define-macros-order
const props = defineProps<IGraphValidateCodeProps>();
const emit = defineEmits<{
(e: 'onEmitOnBlur'): void;
(e: 'onEmitOnChange'): void;
(e: 'onEmitOnFocus'): void;
}>();
defineOptions({
name: 'GraphValidateCode',
});
interface IGraphValidateCodeProps {
/** 获取图片Api接口 */
api?: () => Promise<string>;
/** 校验失败状态 */
validateFailed: boolean;
}
// eslint-disable-next-line vue/define-macros-order
const props = defineProps<IGraphValidateCodeProps>();
/** @event {() => void} blur - Emitted when input loses focus */
/** @event {() => void} change - Emitted when input value changes */
/** @event {() => void} focus - Emitted when input gains focus */
const emit = defineEmits<{
(e: 'blur'): void;
(e: 'change'): void;
(e: 'focus'): void;
}>();

Comment on lines +32 to +53
const loadImgDataApiFn = () => {
return new Promise((resolve, reject) => {
if (props.propApi) {
imgLoadingStateRef.value = true;
props
.propApi()
.then((res) => {
// console.log('res', res);
imgDataRef.value = res;

resolve(res);
})
.catch((error) => {
console.error('e', error);
reject(error);
})
.finally(() => {
imgLoadingStateRef.value = false;
});
}
});
};
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

Enhance error handling and remove debug code.

  1. Remove commented console.log
  2. Add timeout for API calls
  3. Improve error handling with specific error types
 const loadImgDataApiFn = () => {
-  return new Promise((resolve, reject) => {
+  return new Promise<string>((resolve, reject) => {
     if (props.propApi) {
       imgLoadingStateRef.value = true;
+      const timeoutId = setTimeout(() => {
+        imgLoadingStateRef.value = false;
+        reject(new Error('Request timeout'));
+      }, 10000);
+
       props
         .propApi()
         .then((res) => {
-          // console.log('res', res);
           imgDataRef.value = res;
           resolve(res);
         })
         .catch((error) => {
-          console.error('e', error);
+          const errorMessage = error instanceof Error ? error.message : 'Failed to load image';
+          console.error('Image loading failed:', errorMessage);
           reject(error);
         })
         .finally(() => {
+          clearTimeout(timeoutId);
           imgLoadingStateRef.value = false;
         });
+    } else {
+      reject(new Error('API function not provided'));
     }
   });
 };
📝 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 loadImgDataApiFn = () => {
return new Promise((resolve, reject) => {
if (props.propApi) {
imgLoadingStateRef.value = true;
props
.propApi()
.then((res) => {
// console.log('res', res);
imgDataRef.value = res;
resolve(res);
})
.catch((error) => {
console.error('e', error);
reject(error);
})
.finally(() => {
imgLoadingStateRef.value = false;
});
}
});
};
const loadImgDataApiFn = () => {
return new Promise<string>((resolve, reject) => {
if (props.propApi) {
imgLoadingStateRef.value = true;
const timeoutId = setTimeout(() => {
imgLoadingStateRef.value = false;
reject(new Error('Request timeout'));
}, 10000);
props
.propApi()
.then((res) => {
imgDataRef.value = res;
resolve(res);
})
.catch((error) => {
const errorMessage = error instanceof Error ? error.message : 'Failed to load image';
console.error('Image loading failed:', errorMessage);
reject(error);
})
.finally(() => {
clearTimeout(timeoutId);
imgLoadingStateRef.value = false;
});
} else {
reject(new Error('API function not provided'));
}
});
};

Comment on lines 9 to 12
export function getBase64Img(): string {
const index = Math.floor(Math.random() * 5);
return imgDataList[index];
}
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

Improve random selection implementation and add error handling.

The current implementation has several areas for improvement:

  1. Uses Math.random() which isn't cryptographically secure
  2. No error handling for empty array
  3. Hardcoded array length

Consider this more robust implementation:

-export function getBase64Img(): string {
-  const index = Math.floor(Math.random() * 5);
-  return imgDataList[index];
-}
+export function getBase64Img(): string {
+  if (!imgDataList.length) {
+    throw new Error('No validation images available');
+  }
+  // Use crypto for better randomness
+  const array = new Uint32Array(1);
+  crypto.getRandomValues(array);
+  const index = array[0] % imgDataList.length;
+  return imgDataList[index];
+}
📝 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
export function getBase64Img(): string {
const index = Math.floor(Math.random() * 5);
return imgDataList[index];
}
export function getBase64Img(): string {
if (!imgDataList.length) {
throw new Error('No validation images available');
}
// Use crypto for better randomness
const array = new Uint32Array(1);
crypto.getRandomValues(array);
const index = array[0] % imgDataList.length;
return imgDataList[index];
}

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 (1)
playground/src/views/examples/form/costom-sub/img.data.ts (1)

1-7: Consider externalizing image data and improving type safety.

The current implementation has several areas for improvement:

  1. Large base64 strings in source code reduce readability and maintainability
  2. Array type could be more specific than string[]

Consider these improvements:

  1. Move images to separate files:
-const imgDataList: string[] = [
+import img1 from './assets/validation-1.png';
+import img2 from './assets/validation-2.png';
+// ... more imports
+
+const imgDataList: readonly string[] = [
+  img1,
+  img2,
+  // ... more images
];
  1. Add type safety:
-const imgDataList: string[] = [
+type Base64Image = `data:image/png;base64,${string}`;
+const imgDataList: readonly Base64Image[] = [
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e12b35c and 84534d0.

📒 Files selected for processing (2)
  • playground/src/views/examples/form/costom-sub/graph-validate-code.vue (1 hunks)
  • playground/src/views/examples/form/costom-sub/img.data.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • playground/src/views/examples/form/costom-sub/graph-validate-code.vue
🔇 Additional comments (1)
playground/src/views/examples/form/costom-sub/img.data.ts (1)

9-12: 🛠️ Refactor suggestion

Previous review comments about random selection implementation are still valid.

The current implementation could be improved for security and robustness.

In addition to the previous review suggestions about using crypto.getRandomValues(), consider removing the unnecessary type assertion:

 export function getBase64Img(): string {
   const index = Math.floor(Math.random() * 5);
-  return imgDataList[index] as string;
+  return imgDataList[index];
 }

@GavinLucky GavinLucky closed this Dec 2, 2024
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