initializeFieldDefinition.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright (C) 2012-2024 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.ts'
  5. import {
  6. outer,
  7. inner,
  8. wrapper,
  9. icon,
  10. help,
  11. messages,
  12. message,
  13. prefix,
  14. suffix,
  15. label,
  16. } from '@formkit/inputs'
  17. import { block } from '../sections/block.ts'
  18. import { arrow } from '../sections/arrow.ts'
  19. import { link } from '../sections/link.ts'
  20. import defaulfFieldDefinition from './defaultFieldDefinition.ts'
  21. export interface FieldsCustomOptions {
  22. addDefaultProps?: boolean
  23. addDefaultFeatures?: boolean
  24. addArrow?: boolean
  25. schema?: () => FormKitSchemaExtendableSection
  26. }
  27. const initializeFieldDefinition = (
  28. definition: FormKitTypeDefinition,
  29. additionalDefinitionOptions: Pick<
  30. FormKitTypeDefinition,
  31. 'props' | 'features'
  32. > = {},
  33. options: FieldsCustomOptions = {},
  34. ) => {
  35. const {
  36. addDefaultProps = true,
  37. addDefaultFeatures = true,
  38. addArrow = false,
  39. } = options
  40. const localDefinition = definition
  41. localDefinition.props = Array.isArray(localDefinition.props)
  42. ? localDefinition.props
  43. : []
  44. localDefinition.features ||= []
  45. if (options.schema) {
  46. const wrapperSchema = wrapper(
  47. label('$label'),
  48. inner(
  49. icon('prefix', 'label'),
  50. prefix(),
  51. options.schema(),
  52. suffix(),
  53. icon('suffix'),
  54. ),
  55. )
  56. const blockSchema = [wrapperSchema]
  57. if (addArrow) {
  58. blockSchema.push(arrow())
  59. }
  60. blockSchema.push(link())
  61. localDefinition.schema = outer(
  62. block(...blockSchema),
  63. help('$help'),
  64. messages(message('$message.value')),
  65. )
  66. }
  67. const additionalProps = Array.isArray(additionalDefinitionOptions.props)
  68. ? additionalDefinitionOptions.props
  69. : []
  70. if (addDefaultProps) {
  71. const defaulfFieldDefinitionProps = Array.isArray(
  72. defaulfFieldDefinition.props,
  73. )
  74. ? defaulfFieldDefinition.props
  75. : []
  76. localDefinition.props = mergeArray(
  77. localDefinition.props,
  78. defaulfFieldDefinitionProps.concat(additionalProps),
  79. )
  80. }
  81. const additionalFeatures = additionalDefinitionOptions.features || []
  82. if (addDefaultFeatures) {
  83. localDefinition.features = mergeArray(
  84. defaulfFieldDefinition.features.concat(additionalFeatures),
  85. localDefinition.features,
  86. )
  87. }
  88. }
  89. export default initializeFieldDefinition