createFieldPlugin.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import {
  3. createLibraryPlugin as formKitCreateLibraryPlugin,
  4. form as formFieldDefinition,
  5. } from '@formkit/inputs'
  6. import { isArray } from 'lodash-es'
  7. import type {
  8. FormFieldTypeImportModules,
  9. FormFieldsTypeDefinition,
  10. } from '#shared/types/form.ts'
  11. import type {
  12. ImportGlobEagerDefault,
  13. ImportGlobEagerOutput,
  14. } from '#shared/types/utils.ts'
  15. import type { FormKitPlugin } from '@formkit/core'
  16. const fieldModules: ImportGlobEagerOutput<FormFieldTypeImportModules> =
  17. import.meta.glob('../../components/Form/fields/**/index.ts', { eager: true })
  18. // The main field type "form" from FormKit is a fixed type.
  19. const fields: FormFieldsTypeDefinition = {
  20. form: formFieldDefinition,
  21. }
  22. const registerFieldFromModules = (
  23. fieldModules: ImportGlobEagerOutput<FormFieldTypeImportModules>,
  24. ) => {
  25. Object.values(fieldModules).forEach(
  26. (module: ImportGlobEagerDefault<FormFieldTypeImportModules>) => {
  27. const formFieldTypes = module.default
  28. // A object with multiple fields will be returned in the case that one field nidzke handles multiple fields.
  29. // E.g. the FormKit default input fields (text, color, ...).
  30. if (isArray(formFieldTypes)) {
  31. formFieldTypes.forEach((formFieldType) => {
  32. fields[formFieldType.fieldType] = formFieldType.definition
  33. })
  34. } else {
  35. fields[formFieldTypes.fieldType] = formFieldTypes.definition
  36. }
  37. },
  38. )
  39. }
  40. const createFieldPlugin = (
  41. appSpecificFieldModues?: ImportGlobEagerOutput<FormFieldTypeImportModules>,
  42. ): FormKitPlugin => {
  43. // Register first the common fields and then the app specific fields so
  44. // that the app specific fields can override the common ones.
  45. registerFieldFromModules(fieldModules)
  46. if (appSpecificFieldModues) {
  47. registerFieldFromModules(appSpecificFieldModues)
  48. }
  49. return formKitCreateLibraryPlugin(fields)
  50. }
  51. export default createFieldPlugin