extendDataAttributes.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { isEmpty } from 'lodash-es'
  3. import extendSchemaDefinition from '#shared/form/utils/extendSchemaDefinition.ts'
  4. import type { FormKitNode } from '@formkit/core'
  5. import type { FormKitValidation } from '@formkit/validation'
  6. const extendDataAttribues = (node: FormKitNode) => {
  7. const { props, context } = node
  8. if (!props.definition || !context) return
  9. context.fns.includes = (array: unknown[], value: unknown): boolean => {
  10. if (!Array.isArray(array)) return false
  11. return array.includes(value)
  12. }
  13. if (node.type !== 'input') return
  14. // Add the parsedRules as props, so that the value is reactive and
  15. // `$parsedRules` can be used in the if condition (https://github.com/formkit/formkit/issues/356).
  16. node.addProps(['parsedRules'])
  17. // Adds a helper function to check the existing value inside of the context.
  18. context.fns.hasValue = (value: unknown): boolean => {
  19. if (typeof value === 'object') return !isEmpty(value)
  20. return value != null && value !== ''
  21. }
  22. context.fns.hasRule = (
  23. parsedRules: FormKitValidation[],
  24. ruleName: string,
  25. ) => {
  26. return parsedRules.some((rule) => rule.name === ruleName)
  27. }
  28. extendSchemaDefinition(node, 'outer', {
  29. attrs: {
  30. 'data-populated': {
  31. if: '$fns.hasValue($value)',
  32. then: 'true',
  33. else: undefined,
  34. },
  35. 'data-label-hidden': {
  36. if: '$labelSrOnly === true',
  37. then: 'true',
  38. else: undefined,
  39. },
  40. 'data-required': {
  41. if: "$fns.hasRule($parsedRules, 'required')",
  42. then: 'true',
  43. else: undefined,
  44. },
  45. 'data-dirty': {
  46. if: '$state.dirty',
  47. then: 'true',
  48. else: undefined,
  49. },
  50. 'data-triggers-form-updater': {
  51. if: '$triggerFormUpdater',
  52. then: 'true',
  53. else: undefined,
  54. },
  55. },
  56. })
  57. }
  58. export default extendDataAttribues