initializeFieldDefinition.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import type { FormKitTypeDefinition } from '@formkit/core'
  3. import type { FormKitSchemaExtendableSection } from '@formkit/inputs'
  4. import { mergeArray } from '@shared/utils/helpers'
  5. import {
  6. outer,
  7. inner,
  8. wrapper,
  9. label,
  10. help,
  11. messages,
  12. message,
  13. prefix,
  14. suffix,
  15. } from '@formkit/inputs'
  16. import { block } from '../sections/block'
  17. import { arrow } from '../sections/arrow'
  18. import { link } from '../sections/link'
  19. import defaulfFieldDefinition from './defaultFieldDefinition'
  20. export interface FieldsCustomOptions {
  21. addDefaultProps?: boolean
  22. addDefaultFeatures?: boolean
  23. addArrow?: boolean
  24. schema?: () => FormKitSchemaExtendableSection
  25. }
  26. const initializeFieldDefinition = (
  27. definition: FormKitTypeDefinition,
  28. additionalDefinitionOptions: Pick<
  29. FormKitTypeDefinition,
  30. 'props' | 'features'
  31. > = {},
  32. options: FieldsCustomOptions = {},
  33. ) => {
  34. const {
  35. addDefaultProps = true,
  36. addDefaultFeatures = true,
  37. addArrow = false,
  38. } = options
  39. const localDefinition = definition
  40. localDefinition.props ||= []
  41. localDefinition.features ||= []
  42. if (options.schema) {
  43. const wrapperSchema = wrapper(
  44. label('$label'),
  45. inner(prefix(), options.schema(), suffix()),
  46. )
  47. const blockSchema = [wrapperSchema]
  48. if (addArrow) {
  49. blockSchema.push(arrow())
  50. }
  51. blockSchema.push(link())
  52. localDefinition.schema = outer(
  53. block(...blockSchema),
  54. help('$help'),
  55. messages(message('$message.value')),
  56. )
  57. }
  58. const additionalProps = additionalDefinitionOptions.props || []
  59. if (addDefaultProps) {
  60. localDefinition.props = mergeArray(
  61. localDefinition.props,
  62. defaulfFieldDefinition.props.concat(additionalProps),
  63. )
  64. }
  65. const additionalFeatures = additionalDefinitionOptions.features || []
  66. if (addDefaultFeatures) {
  67. localDefinition.features = mergeArray(
  68. defaulfFieldDefinition.features.concat(additionalFeatures),
  69. localDefinition.features,
  70. )
  71. }
  72. }
  73. export default initializeFieldDefinition