config.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import type {
  2. BaseFormComponentType,
  3. FormCommonConfig,
  4. VbenFormAdapterOptions,
  5. } from './types';
  6. import type { Component } from 'vue';
  7. import { h } from 'vue';
  8. import {
  9. VbenButton,
  10. VbenCheckbox,
  11. Input as VbenInput,
  12. VbenInputPassword,
  13. VbenPinInput,
  14. VbenSelect,
  15. } from '@vben-core/shadcn-ui';
  16. import { defineRule } from 'vee-validate';
  17. const DEFAULT_MODEL_PROP_NAME = 'modelValue';
  18. export const DEFAULT_FORM_COMMON_CONFIG: FormCommonConfig = {};
  19. export const COMPONENT_MAP: Record<BaseFormComponentType, Component> = {
  20. DefaultResetActionButton: h(VbenButton, { size: 'sm', variant: 'outline' }),
  21. DefaultSubmitActionButton: h(VbenButton, { size: 'sm', variant: 'default' }),
  22. VbenCheckbox,
  23. VbenInput,
  24. VbenInputPassword,
  25. VbenPinInput,
  26. VbenSelect,
  27. };
  28. export const COMPONENT_BIND_EVENT_MAP: Partial<
  29. Record<BaseFormComponentType, string>
  30. > = {
  31. VbenCheckbox: 'checked',
  32. };
  33. export function setupVbenForm<
  34. T extends BaseFormComponentType = BaseFormComponentType,
  35. >(options: VbenFormAdapterOptions<T>) {
  36. const { components, config, defineRules } = options;
  37. const { disabledOnChangeListener = false, emptyStateValue = undefined } =
  38. (config || {}) as FormCommonConfig;
  39. Object.assign(DEFAULT_FORM_COMMON_CONFIG, {
  40. disabledOnChangeListener,
  41. emptyStateValue,
  42. });
  43. if (defineRules) {
  44. for (const key of Object.keys(defineRules)) {
  45. defineRule(key, defineRules[key as never]);
  46. }
  47. }
  48. const baseModelPropName =
  49. config?.baseModelPropName ?? DEFAULT_MODEL_PROP_NAME;
  50. const modelPropNameMap = config?.modelPropNameMap as
  51. | Record<BaseFormComponentType, string>
  52. | undefined;
  53. for (const component of Object.keys(components)) {
  54. const key = component as BaseFormComponentType;
  55. COMPONENT_MAP[key] = components[component as never];
  56. if (baseModelPropName !== DEFAULT_MODEL_PROP_NAME) {
  57. COMPONENT_BIND_EVENT_MAP[key] = baseModelPropName;
  58. }
  59. // 覆盖特殊组件的modelPropName
  60. if (modelPropNameMap && modelPropNameMap[key]) {
  61. COMPONENT_BIND_EVENT_MAP[key] = modelPropNameMap[key];
  62. }
  63. }
  64. }