config.ts 2.2 KB

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