addIcon.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import type { FormKitNode } from '@formkit/core'
  3. import { FormSchemaExtendType } from '@shared/types/form'
  4. import extendSchemaDefinition from '../utils/extendSchemaDefinition'
  5. const addIcon = (node: FormKitNode) => {
  6. node.addProps(['iconPosition', 'icon', 'onIconClick'])
  7. if (
  8. !node.props.definition ||
  9. typeof node.props.definition.schema !== 'function'
  10. ) {
  11. return
  12. }
  13. const iconPosition = node.props.iconPosition || 'prefix'
  14. const initalizeIconClickHandler = () => {
  15. if (!node.props.icon) return
  16. if (node.context && node.props.onIconClick) {
  17. node.context.onIconClick = node.props.onIconClick
  18. const iconClick = () => {
  19. if (typeof node.context?.onIconClick === 'function') {
  20. node.context.onIconClick(node)
  21. }
  22. }
  23. node.context.handleIconClick = iconClick.bind(null)
  24. }
  25. }
  26. node.on('created', () => {
  27. initalizeIconClickHandler()
  28. })
  29. extendSchemaDefinition(
  30. node,
  31. iconPosition,
  32. {
  33. if: '$icon',
  34. $el: 'span',
  35. children: [
  36. {
  37. $cmp: 'CommonIcon',
  38. props: {
  39. name: '$icon',
  40. key: node.name,
  41. class: `absolute top-1/2 transform -translate-y-1/2 ${
  42. iconPosition === 'prefix' ? 'left-3' : 'right-3'
  43. }`,
  44. size: 'small',
  45. onClick: {
  46. if: '$onIconClick',
  47. then: `$handleIconClick`,
  48. },
  49. },
  50. },
  51. ],
  52. },
  53. FormSchemaExtendType.Prepend,
  54. )
  55. }
  56. export default addIcon