extendSchemaDefinition.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { extend } from '@formkit/utils'
  3. import { cloneDeep } from 'lodash-es'
  4. import { FormSchemaExtendType } from '#shared/types/form.ts'
  5. import type {
  6. FormKitExtendableSchemaRoot,
  7. FormKitNode,
  8. FormKitSchemaCondition,
  9. FormKitSchemaNode,
  10. } from '@formkit/core'
  11. // Can later be switched to in built-in feature from FormKit (when it's available).
  12. const extendSchemaDefinition = (
  13. node: FormKitNode,
  14. sectionKey: string,
  15. schemaExtension: FormKitSchemaCondition | Partial<FormKitSchemaNode>,
  16. extendType: FormSchemaExtendType = FormSchemaExtendType.Merge,
  17. cloneDefinition = false,
  18. // eslint-disable-next-line sonarjs/cognitive-complexity
  19. ) => {
  20. const { props } = node
  21. if (!props.definition) return
  22. const definition = cloneDefinition
  23. ? cloneDeep(props.definition)
  24. : props.definition
  25. const originalSchema = definition.schema as FormKitExtendableSchemaRoot
  26. definition.schema = (extensions) => {
  27. let sectionSchemaExtension:
  28. | FormKitSchemaCondition
  29. | Partial<FormKitSchemaNode>
  30. const currentExtension = extensions[sectionKey] || {}
  31. if (extendType === FormSchemaExtendType.Merge) {
  32. // When current extenstions is a string, replace it.
  33. if (typeof currentExtension === 'string') {
  34. sectionSchemaExtension = schemaExtension
  35. } else {
  36. sectionSchemaExtension = extend(currentExtension, schemaExtension) as
  37. | FormKitSchemaCondition
  38. | Partial<FormKitSchemaNode>
  39. }
  40. } else if (extendType === FormSchemaExtendType.Replace) {
  41. sectionSchemaExtension = schemaExtension
  42. } else {
  43. let currentChildren: Maybe<
  44. (FormKitSchemaCondition | Partial<FormKitSchemaNode>)[]
  45. > = null
  46. if (
  47. currentExtension &&
  48. typeof currentExtension === 'object' &&
  49. 'children' in currentExtension &&
  50. Array.isArray(currentExtension.children)
  51. ) {
  52. currentChildren = currentExtension.children
  53. }
  54. if (currentChildren) {
  55. sectionSchemaExtension = {
  56. children:
  57. extendType === FormSchemaExtendType.Append
  58. ? [...currentChildren, schemaExtension]
  59. : [schemaExtension, ...currentChildren],
  60. } as Partial<FormKitSchemaNode>
  61. } else {
  62. sectionSchemaExtension = {
  63. children: [schemaExtension],
  64. } as Partial<FormKitSchemaNode>
  65. }
  66. }
  67. const localExtensions = {
  68. ...extensions,
  69. [sectionKey]: sectionSchemaExtension,
  70. }
  71. return originalSchema(localExtensions)
  72. }
  73. props.definition = definition
  74. }
  75. export default extendSchemaDefinition