-
Notifications
You must be signed in to change notification settings - Fork 6.9k
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
base: main
Are you sure you want to change the base?
Conversation
|
WalkthroughThis pull request introduces a new Vue component, Changes
Possibly related PRs
Suggested labels
Suggested reviewers
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
playground/src/views/examples/form/costom-sub/graph-validate-code.vueOops! 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 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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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.
- Remove debug comments
- Add proper type for change event
- 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.
- The arbitrary 100ms delay in
onMounted
seems unnecessary- 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.
- Add meaningful alt text for the validation image
- Consider making dimensions configurable via props
- 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 pathsThe 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 getImgApiThe 500ms delay might negatively impact user experience. Consider:
- Reducing the delay if it's for testing purposes
- Removing it if it's not necessary for production
- 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 configurationBoth 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 handlersThe current implementation has some redundancies in event naming and an empty handler:
- The 'on-emit-on-' prefix is redundant
- 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:
- Storing large base64 strings in source code reduces maintainability and increases bundle size
- A limited set of 5 hardcoded images makes the validation codes predictable and less secure
Consider these alternatives:
- Store images in separate files and load them dynamically
- Use a server-side API to generate random validation codes
- Use a client-side canvas to generate dynamic validation codes
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 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
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; | ||
}>(); |
There was a problem hiding this comment.
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.
-
Event names should follow Vue's conventions:
- Remove redundant 'onEmit' prefix
- Use kebab-case for event names
-
Props could be more concise:
propApi
→api
propValidateFailed
→validateFailed
-
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.
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; | |
}>(); |
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; | ||
}); | ||
} | ||
}); | ||
}; |
There was a problem hiding this comment.
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.
- Remove commented console.log
- Add timeout for API calls
- 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.
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')); | |
} | |
}); | |
}; |
export function getBase64Img(): string { | ||
const index = Math.floor(Math.random() * 5); | ||
return imgDataList[index]; | ||
} |
There was a problem hiding this comment.
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:
- Uses Math.random() which isn't cryptographically secure
- No error handling for empty array
- 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.
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]; | |
} |
There was a problem hiding this 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:
- Large base64 strings in source code reduce readability and maintainability
- Array type could be more specific than
string[]
Consider these improvements:
- 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 ];
- 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
📒 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];
}
Description
Type of change
Please delete options that are not relevant.
pnpm-lock.yaml
unless you introduce a new test example.Checklist
pnpm run docs:dev
command.pnpm test
.feat:
,fix:
,perf:
,docs:
, orchore:
.Summary by CodeRabbit
New Features
GraphValidateCode
component for handling graphical validation codes.getBase64Img
function to retrieve random base64-encoded images.GraphValidateCode
component.Bug Fixes
Documentation