chore: code format

This commit is contained in:
xiaojunnuo
2025-06-29 14:09:09 +08:00
parent 04422a4637
commit 4fcfd089d8
644 changed files with 10845 additions and 13184 deletions
@@ -18,7 +18,7 @@ const resetButtonOptions = computed(() => {
return {
content: `${$t.value("reset")}`,
show: true,
...unref(rootProps).resetButtonOptions
...unref(rootProps).resetButtonOptions,
};
});
@@ -26,7 +26,7 @@ const submitButtonOptions = computed(() => {
return {
content: `${$t.value("submit")}`,
show: true,
...unref(rootProps).submitButtonOptions
...unref(rootProps).submitButtonOptions,
};
});
@@ -38,7 +38,7 @@ const queryFormStyle = computed(() => {
if (!unref(rootProps).actionWrapperClass) {
return {
"grid-column": `-2 / -1`,
marginLeft: "auto"
marginLeft: "auto",
};
}
@@ -83,7 +83,7 @@ watch(
defineExpose({
handleReset,
handleSubmit
handleSubmit,
});
</script>
<template>
@@ -20,11 +20,11 @@ export const COMPONENT_MAP: Record<BaseFormComponentType, Component> = {
VbenInput,
VbenInputPassword,
VbenPinInput,
VbenSelect
VbenSelect,
};
export const COMPONENT_BIND_EVENT_MAP: Partial<Record<BaseFormComponentType, string>> = {
VbenCheckbox: "checked"
VbenCheckbox: "checked",
};
export function setupVbenForm<T extends BaseFormComponentType = BaseFormComponentType>(options: VbenFormAdapterOptions<T>) {
@@ -35,7 +35,7 @@ export function setupVbenForm<T extends BaseFormComponentType = BaseFormComponen
Object.assign(DEFAULT_FORM_COMMON_CONFIG, {
disabledOnChangeListener,
disabledOnInputListener,
emptyStateValue
emptyStateValue,
});
if (defineRules) {
@@ -27,7 +27,7 @@ function getDefaultState(): VbenFormProps {
submitButtonOptions: {},
submitOnChange: false,
submitOnEnter: false,
wrapperClass: "grid-cols-1"
wrapperClass: "grid-cols-1",
};
}
@@ -54,14 +54,14 @@ export class FormApi {
this.store = new Store<VbenFormProps>(
{
...defaultState,
...storeState
...storeState,
},
{
onUpdate: () => {
this.prevState = this.state;
this.state = this.store.state;
this.updateState();
}
},
}
);
@@ -102,7 +102,7 @@ export class FormApi {
return async (needMerge: boolean = true) => {
try {
const results = await Promise.all(
chain.map(async (api) => {
chain.map(async api => {
const validateResult = await api.validate();
if (!validateResult.valid) {
return;
@@ -122,7 +122,7 @@ export class FormApi {
};
}
return target[prop];
}
},
});
return proxy;
@@ -133,7 +133,7 @@ export class FormApi {
Object.assign(this.form, formActions);
this.stateHandler.setConditionTrue();
this.setLatestSubmissionValues({
...toRaw(this.handleRangeTimeValue(this.form.values))
...toRaw(this.handleRangeTimeValue(this.form.values)),
});
this.isMounted = true;
}
@@ -147,10 +147,10 @@ export class FormApi {
const fieldSet = new Set(fields);
const schema = this.state?.schema ?? [];
const filterSchema = schema.filter((item) => !fieldSet.has(item.fieldName));
const filterSchema = schema.filter(item => !fieldSet.has(item.fieldName));
this.setState({
schema: filterSchema
schema: filterSchema,
});
}
@@ -165,7 +165,7 @@ export class FormApi {
async resetValidate() {
const form = await this.getForm();
const fields = Object.keys(form.errors.value);
fields.forEach((field) => {
fields.forEach(field => {
form.setFieldError(field, undefined);
});
}
@@ -181,11 +181,11 @@ export class FormApi {
setState(stateOrFn: ((prev: VbenFormProps) => Partial<VbenFormProps>) | Partial<VbenFormProps>) {
if (isFunction(stateOrFn)) {
this.store.setState((prev) => {
this.store.setState(prev => {
return mergeWithArrayOverride(stateOrFn(prev), prev);
});
} else {
this.store.setState((prev) => mergeWithArrayOverride(stateOrFn, prev));
this.store.setState(prev => mergeWithArrayOverride(stateOrFn, prev));
}
}
@@ -239,7 +239,7 @@ export class FormApi {
updateSchema(schema: Partial<FormSchema>[]) {
const updated: Partial<FormSchema>[] = [...schema];
const hasField = updated.every((item) => Reflect.has(item, "fieldName") && item.fieldName);
const hasField = updated.every(item => Reflect.has(item, "fieldName") && item.fieldName);
if (!hasField) {
console.error("All items in the schema array must have a valid `fieldName` property to be updated");
@@ -249,7 +249,7 @@ export class FormApi {
const updatedMap: Record<string, any> = {};
updated.forEach((item) => {
updated.forEach(item => {
if (item.fieldName) {
updatedMap[item.fieldName] = item;
}
@@ -351,8 +351,8 @@ export class FormApi {
const prevSchema = this.prevState?.schema ?? [];
// 进行了删除schema操作
if (currentSchema.length < prevSchema.length) {
const currentFields = new Set(currentSchema.map((item) => item.fieldName));
const deletedSchema = prevSchema.filter((item) => !currentFields.has(item.fieldName));
const currentFields = new Set(currentSchema.map(item => item.fieldName));
const deletedSchema = prevSchema.filter(item => !currentFields.has(item.fieldName));
for (const schema of deletedSchema) {
this.form?.setFieldValue?.(schema.fieldName, undefined);
}
@@ -16,6 +16,6 @@ export const useFormContext = () => {
return {
componentBindEventMap,
componentMap,
isVertical
isVertical,
};
};
@@ -30,7 +30,7 @@ export default function useDependencies(getDependencies: () => FormItemDependenc
const triggerFieldValues = computed(() => {
// 该字段可能会被多个字段触发
const triggerFields = getDependencies()?.triggerFields ?? [];
return triggerFields.map((dep) => {
return triggerFields.map(dep => {
return values.value[dep];
});
});
@@ -105,6 +105,6 @@ export default function useDependencies(getDependencies: () => FormItemDependenc
isDisabled,
isIf,
isRequired,
isShow
isShow,
};
}
@@ -59,7 +59,7 @@ export function useExpandable(props: FormRenderProps) {
const containerRect = container?.getBoundingClientRect();
formItems.forEach((el) => {
formItems.forEach(el => {
const itemRect = el.getBoundingClientRect();
// 计算元素在第几行
@@ -1,27 +1,20 @@
<script setup lang="ts">
import type { ZodType } from 'zod';
import type { ZodType } from "zod";
import type { FormSchema, MaybeComponentProps } from '../types';
import type { FormSchema, MaybeComponentProps } from "../types";
import { computed, nextTick, useTemplateRef, watch } from 'vue';
import { computed, nextTick, useTemplateRef, watch } from "vue";
import {
FormControl,
FormDescription,
FormField,
FormItem,
FormMessage,
VbenRenderContent,
} from '/@/vben/shadcn-ui';
import { cn, isFunction, isObject, isString } from '/@/vben/shared/utils';
import { FormControl, FormDescription, FormField, FormItem, FormMessage, VbenRenderContent } from "/@/vben/shadcn-ui";
import { cn, isFunction, isObject, isString } from "/@/vben/shared/utils";
import { toTypedSchema } from '@vee-validate/zod';
import { useFieldError, useFormValues } from 'vee-validate';
import { toTypedSchema } from "@vee-validate/zod";
import { useFieldError, useFormValues } from "vee-validate";
import { injectRenderFormProps, useFormContext } from './context';
import useDependencies from './dependencies';
import FormLabel from './form-label.vue';
import { isEventObjectLike } from './helper';
import { injectRenderFormProps, useFormContext } from "./context";
import useDependencies from "./dependencies";
import FormLabel from "./form-label.vue";
import { isEventObjectLike } from "./helper";
interface Props extends FormSchema {}
@@ -54,15 +47,13 @@ const { componentBindEventMap, componentMap, isVertical } = useFormContext();
const formRenderProps = injectRenderFormProps();
const values = useFormValues();
const errors = useFieldError(fieldName);
const fieldComponentRef = useTemplateRef<HTMLInputElement>('fieldComponentRef');
const fieldComponentRef = useTemplateRef<HTMLInputElement>("fieldComponentRef");
const formApi = formRenderProps.form;
const compact = formRenderProps.compact;
const isInValid = computed(() => errors.value?.length > 0);
const FieldComponent = computed(() => {
const finalComponent = isString(component)
? componentMap.value[component]
: component;
const finalComponent = isString(component) ? componentMap.value[component] : component;
if (!finalComponent) {
// 组件未注册
console.warn(`Component ${component} is not registered`);
@@ -70,17 +61,10 @@ const FieldComponent = computed(() => {
return finalComponent;
});
const {
dynamicComponentProps,
dynamicRules,
isDisabled,
isIf,
isRequired,
isShow,
} = useDependencies(() => dependencies);
const { dynamicComponentProps, dynamicRules, isDisabled, isIf, isRequired, isShow } = useDependencies(() => dependencies);
const labelStyle = computed(() => {
return labelClass?.includes('w-') || isVertical.value
return labelClass?.includes("w-") || isVertical.value
? {}
: {
width: `${labelWidth}px`,
@@ -109,14 +93,14 @@ const shouldRequired = computed(() => {
}
if (isString(currentRules.value)) {
return ['required', 'selectRequired'].includes(currentRules.value);
return ["required", "selectRequired"].includes(currentRules.value);
}
let isOptional = currentRules?.value?.isOptional?.();
// 如果有设置默认值,则不是必填,需要特殊处理
const typeName = currentRules?.value?._def?.typeName;
if (typeName === 'ZodDefault') {
if (typeName === "ZodDefault") {
const innerType = currentRules?.value?._def.innerType;
if (innerType) {
isOptional = innerType.isOptional?.();
@@ -133,7 +117,7 @@ const fieldRules = computed(() => {
let rules = currentRules.value;
if (!rules) {
return isRequired.value ? 'required' : null;
return isRequired.value ? "required" : null;
}
if (isString(rules)) {
@@ -151,9 +135,7 @@ const fieldRules = computed(() => {
});
const computedProps = computed(() => {
const finalComponentProps = isFunction(componentProps)
? componentProps(values.value, formApi!)
: componentProps;
const finalComponentProps = isFunction(componentProps) ? componentProps(values.value, formApi!) : componentProps;
return {
...commonComponentProps,
@@ -164,14 +146,14 @@ const computedProps = computed(() => {
watch(
() => computedProps.value?.autofocus,
(value) => {
value => {
if (value === true) {
nextTick(() => {
autofocus();
});
}
},
{ immediate: true },
{ immediate: true }
);
const shouldDisabled = computed(() => {
@@ -193,7 +175,7 @@ const fieldProps = computed(() => {
const rules = fieldRules.value;
return {
keepValue: true,
label: isString(label) ? label : '',
label: isString(label) ? label : "",
...(rules ? { rules } : {}),
...(formFieldProps as Record<string, any>),
};
@@ -201,18 +183,14 @@ const fieldProps = computed(() => {
function fieldBindEvent(slotProps: Record<string, any>) {
const modelValue = slotProps.componentField.modelValue;
const handler = slotProps.componentField['onUpdate:modelValue'];
const handler = slotProps.componentField["onUpdate:modelValue"];
const bindEventField =
modelPropName ||
(isString(component) ? componentBindEventMap.value?.[component] : null);
const bindEventField = modelPropName || (isString(component) ? componentBindEventMap.value?.[component] : null);
let value = modelValue;
// antd design 的一些组件会传递一个 event 对象
if (modelValue && isObject(modelValue) && bindEventField) {
value = isEventObjectLike(modelValue)
? modelValue?.target?.[bindEventField]
: (modelValue?.[bindEventField] ?? modelValue);
value = isEventObjectLike(modelValue) ? modelValue?.target?.[bindEventField] : (modelValue?.[bindEventField] ?? modelValue);
}
if (bindEventField) {
@@ -246,12 +224,8 @@ function createComponentProps(slotProps: Record<string, any>) {
...slotProps.componentField,
...computedProps.value,
...bindEvents,
...(Reflect.has(computedProps.value, 'onChange')
? { onChange: computedProps.value.onChange }
: {}),
...(Reflect.has(computedProps.value, 'onInput')
? { onInput: computedProps.value.onInput }
: {}),
...(Reflect.has(computedProps.value, "onChange") ? { onChange: computedProps.value.onChange } : {}),
...(Reflect.has(computedProps.value, "onInput") ? { onInput: computedProps.value.onInput } : {}),
};
return binds;
@@ -270,12 +244,7 @@ function autofocus() {
</script>
<template>
<FormField
v-if="isIf"
v-bind="fieldProps"
v-slot="slotProps"
:name="fieldName"
>
<FormField v-if="isIf" v-slot="slotProps" v-bind="fieldProps" :name="fieldName">
<FormItem
v-show="isShow"
:class="{
@@ -297,7 +266,7 @@ function autofocus() {
'mr-2 flex-shrink-0 justify-end': !isVertical,
'mb-1 flex-row': isVertical,
},
labelClass,
labelClass
)
"
:help="help"
@@ -326,21 +295,13 @@ function autofocus() {
:is="FieldComponent"
ref="fieldComponentRef"
:class="{
'border-destructive focus:border-destructive hover:border-destructive/80 focus:shadow-[0_0_0_2px_rgba(255,38,5,0.06)]':
isInValid,
'border-destructive focus:border-destructive hover:border-destructive/80 focus:shadow-[0_0_0_2px_rgba(255,38,5,0.06)]': isInValid,
}"
v-bind="createComponentProps(slotProps)"
:disabled="shouldDisabled"
>
<template
v-for="name in renderContentKey"
:key="name"
#[name]="renderSlotProps"
>
<VbenRenderContent
:content="customContentRender[name]"
v-bind="{ ...renderSlotProps, formContext: slotProps }"
/>
<template v-for="name in renderContentKey" :key="name" #[name]="renderSlotProps">
<VbenRenderContent :content="customContentRender[name]" v-bind="{ ...renderSlotProps, formContext: slotProps }" />
</template>
<!-- <slot></slot> -->
</component>
@@ -1,12 +1,8 @@
<script setup lang="ts">
import type { CustomRenderType } from '../types';
import type { CustomRenderType } from "../types";
import {
FormLabel,
VbenHelpTooltip,
VbenRenderContent,
} from '/@/vben/shadcn-ui';
import { cn } from '/@/vben/shared/utils';
import { FormLabel, VbenHelpTooltip, VbenRenderContent } from "/@/vben/shadcn-ui";
import { cn } from "/@/vben/shared/utils";
interface Props {
class?: string;
@@ -21,7 +21,7 @@ const props = withDefaults(defineProps<Props & { globalCommonConfig?: FormCommon
commonConfig: () => ({}),
globalCommonConfig: () => ({}),
showCollapseButton: false,
wrapperClass: "grid-cols-1 sm:grid-cols-2 md:grid-cols-3"
wrapperClass: "grid-cols-1 sm:grid-cols-2 md:grid-cols-3",
});
const emits = defineEmits<{
@@ -34,7 +34,7 @@ const { isCalculated, keepFormItemIndex, wrapperRef } = useExpandable(props);
const shapes = computed(() => {
const resultShapes: FormShape[] = [];
props.schema?.forEach((schema) => {
props.schema?.forEach(schema => {
const { fieldName } = schema;
const rules = schema.rules as ZodTypeAny;
@@ -49,7 +49,7 @@ const shapes = computed(() => {
default: getDefaultValueInZodStack(rules),
fieldName,
required: !["ZodNullable", "ZodOptional"].includes(typeName),
rules: baseRules
rules: baseRules,
});
});
return resultShapes;
@@ -60,10 +60,10 @@ const formComponent = computed(() => (props.form ? "form" : Form));
const formComponentProps = computed(() => {
return props.form
? {
onSubmit: props.form.handleSubmit((val: any) => emits("submit", val))
onSubmit: props.form.handleSubmit((val: any) => emits("submit", val)),
}
: {
onSubmit: (val: GenericObject) => emits("submit", val)
onSubmit: (val: GenericObject) => emits("submit", val),
};
});
@@ -91,7 +91,7 @@ const computedSchema = computed(
labelClass = "",
labelWidth = 100,
modelPropName = "",
wrapperClass = ""
wrapperClass = "",
} = mergeWithArrayOverride(props.commonConfig, props.globalCommonConfig);
return (props.schema || []).map((schema, index) => {
const keepIndex = keepFormItemIndex.value;
@@ -117,10 +117,10 @@ const computedSchema = computed(
controlClass: cn(controlClass, schema.controlClass),
formFieldProps: {
...formFieldProps,
...schema.formFieldProps
...schema.formFieldProps,
},
formItemClass: cn("flex-shrink-0", { hidden }, formItemClass, schema.formItemClass),
labelClass: cn(labelClass, schema.labelClass)
labelClass: cn(labelClass, schema.labelClass),
};
});
}
@@ -1,27 +1,16 @@
import type {
AnyZodObject,
ZodDefault,
ZodEffects,
ZodNumber,
ZodString,
ZodTypeAny,
} from 'zod';
import type { AnyZodObject, ZodDefault, ZodEffects, ZodNumber, ZodString, ZodTypeAny } from "zod";
import { isObject, isString } from '/@/vben/shared/utils';
import { isObject, isString } from "/@/vben/shared/utils";
/**
* Get the lowest level Zod type.
* This will unpack optionals, refinements, etc.
*/
export function getBaseRules<
ChildType extends AnyZodObject | ZodTypeAny = ZodTypeAny,
>(schema: ChildType | ZodEffects<ChildType>): ChildType | null {
export function getBaseRules<ChildType extends AnyZodObject | ZodTypeAny = ZodTypeAny>(schema: ChildType | ZodEffects<ChildType>): ChildType | null {
if (!schema || isString(schema)) return null;
if ('innerType' in schema._def)
return getBaseRules(schema._def.innerType as ChildType);
if ("innerType" in schema._def) return getBaseRules(schema._def.innerType as ChildType);
if ('schema' in schema._def)
return getBaseRules(schema._def.schema as ChildType);
if ("schema" in schema._def) return getBaseRules(schema._def.schema as ChildType);
return schema as ChildType;
}
@@ -35,18 +24,13 @@ export function getDefaultValueInZodStack(schema: ZodTypeAny): any {
}
const typedSchema = schema as unknown as ZodDefault<ZodNumber | ZodString>;
if (typedSchema._def.typeName === 'ZodDefault')
return typedSchema._def.defaultValue();
if (typedSchema._def.typeName === "ZodDefault") return typedSchema._def.defaultValue();
if ('innerType' in typedSchema._def) {
return getDefaultValueInZodStack(
typedSchema._def.innerType as unknown as ZodTypeAny,
);
if ("innerType" in typedSchema._def) {
return getDefaultValueInZodStack(typedSchema._def.innerType as unknown as ZodTypeAny);
}
if ('schema' in typedSchema._def) {
return getDefaultValueInZodStack(
(typedSchema._def as any).schema as ZodTypeAny,
);
if ("schema" in typedSchema._def) {
return getDefaultValueInZodStack((typedSchema._def as any).schema as ZodTypeAny);
}
return undefined;
@@ -56,5 +40,5 @@ export function isEventObjectLike(obj: any) {
if (!obj || !isObject(obj)) {
return false;
}
return Reflect.has(obj, 'target') && Reflect.has(obj, 'stopPropagation');
return Reflect.has(obj, "target") && Reflect.has(obj, "stopPropagation");
}
@@ -1,3 +1,3 @@
export { default as FormField } from './form-field.vue';
export { default as FormLabel } from './form-label.vue';
export { default as Form } from './form.vue';
export { default as FormField } from "./form-field.vue";
export { default as FormLabel } from "./form-label.vue";
export { default as Form } from "./form.vue";
@@ -22,7 +22,7 @@ export function useFormInitial(props: ComputedRef<VbenFormProps> | VbenFormProps
const initialValues = generateInitialValues();
const form = useForm({
...(Object.keys(initialValues)?.length ? { initialValues } : {})
...(Object.keys(initialValues)?.length ? { initialValues } : {}),
});
const delegatedSlots = computed(() => {
@@ -40,7 +40,7 @@ export function useFormInitial(props: ComputedRef<VbenFormProps> | VbenFormProps
const initialValues: Record<string, any> = {};
const zodObject: ZodRawShape = {};
(unref(props).schema || []).forEach((item) => {
(unref(props).schema || []).forEach(item => {
if (Reflect.has(item, "defaultValue")) {
initialValues[item.fieldName] = item.defaultValue;
} else if (item.rules && !isString(item.rules)) {
@@ -55,6 +55,6 @@ export function useFormInitial(props: ComputedRef<VbenFormProps> | VbenFormProps
return {
delegatedSlots,
form
form,
};
}
@@ -11,7 +11,7 @@ export function useVbenForm<T extends BaseFormComponentType = BaseFormComponentT
const IS_REACTIVE = isReactive(options);
const api = new FormApi(options);
const extendedApi: ExtendedFormApi = api as never;
extendedApi.useStore = (selector) => {
extendedApi.useStore = selector => {
return useStore(api.store, selector);
};
@@ -25,7 +25,7 @@ export function useVbenForm<T extends BaseFormComponentType = BaseFormComponentT
},
{
name: "VbenUseForm",
inheritAttrs: false
inheritAttrs: false,
}
);
// Add reactivity support
@@ -24,7 +24,7 @@ const props = withDefaults(defineProps<Props>(), {
showCollapseButton: false,
showDefaultActions: true,
submitButtonOptions: () => ({}),
wrapperClass: "grid-cols-1"
wrapperClass: "grid-cols-1",
});
const forward = useForwardPropsEmits(props);