config.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 { 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 { disabledOnChangeListener = false, emptyStateValue = undefined } =
  39. (config || {}) as FormCommonConfig;
  40. Object.assign(DEFAULT_FORM_COMMON_CONFIG, {
  41. disabledOnChangeListener,
  42. emptyStateValue,
  43. });
  44. if (defineRules) {
  45. for (const key of Object.keys(defineRules)) {
  46. defineRule(key, defineRules[key as never]);
  47. }
  48. }
  49. const baseModelPropName =
  50. config?.baseModelPropName ?? DEFAULT_MODEL_PROP_NAME;
  51. const modelPropNameMap = config?.modelPropNameMap as
  52. | Record<BaseFormComponentType, string>
  53. | undefined;
  54. const components = globalShareState.getComponents();
  55. for (const component of Object.keys(components)) {
  56. const key = component as BaseFormComponentType;
  57. COMPONENT_MAP[key] = components[component as never];
  58. if (baseModelPropName !== DEFAULT_MODEL_PROP_NAME) {
  59. COMPONENT_BIND_EVENT_MAP[key] = baseModelPropName;
  60. }
  61. // 覆盖特殊组件的modelPropName
  62. if (modelPropNameMap && modelPropNameMap[key]) {
  63. COMPONENT_BIND_EVENT_MAP[key] = modelPropNameMap[key];
  64. }
  65. }
  66. }