createFieldPlugin.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { FormKitPlugin } from '@formkit/core'
  3. import {
  4. createLibraryPlugin as formKitCreateLibraryPlugin,
  5. form as formFieldDefinition,
  6. } from '@formkit/inputs'
  7. import { isArray } from 'lodash-es'
  8. import type {
  9. FormFieldTypeImportModules,
  10. FormFieldsTypeDefinition,
  11. } from '#shared/types/form.ts'
  12. import type {
  13. ImportGlobEagerDefault,
  14. ImportGlobEagerOutput,
  15. } from '#shared/types/utils.ts'
  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