translateWrapperProps.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { createMessage } from '@formkit/core'
  3. import { isEmpty } from 'lodash-es'
  4. import { computed } from 'vue'
  5. import { i18n } from '#shared/i18n.ts'
  6. import type { FormKitNode } from '@formkit/core'
  7. import type { ComputedRef } from 'vue'
  8. const propsToTranslate = ['label', 'placeholder', 'help']
  9. const attrsToTranslate = ['placeholder']
  10. const translateAttrs = (node: FormKitNode, attrs: Record<string, string>) => {
  11. const translatedAttrs: Record<string, string | ComputedRef<string>> = {
  12. ...attrs,
  13. }
  14. attrsToTranslate.forEach((attr) => {
  15. if (
  16. attr in attrs &&
  17. (!node.store[attr] || node.store[attr].value !== attrs[attr])
  18. ) {
  19. // Remember the source message.
  20. node.store.set(
  21. createMessage({
  22. key: attr,
  23. type: 'ui',
  24. value: attrs[attr] as string,
  25. }),
  26. )
  27. }
  28. if (node.store[attr] && node.store[attr].value) {
  29. translatedAttrs.placeholder = computed(() => {
  30. return i18n.t(node.store.placeholder.value as string)
  31. })
  32. }
  33. })
  34. return translatedAttrs
  35. }
  36. const translateWrapperProps = (node: FormKitNode) => {
  37. node.hook.prop(({ prop, value }, next) => {
  38. const propName = prop as string
  39. if (propName === 'attrs' && !isEmpty(value)) {
  40. // eslint-disable-next-line vue/no-ref-as-operand
  41. value = translateAttrs(node, value)
  42. }
  43. if (propsToTranslate.includes(propName)) {
  44. // eslint-disable-next-line vue/no-ref-as-operand
  45. if (!node.store[propName] || node.store[propName].value !== value) {
  46. node.store.set(
  47. createMessage({
  48. key: propName,
  49. type: 'ui',
  50. value,
  51. }),
  52. )
  53. }
  54. if (propName === 'label') {
  55. // eslint-disable-next-line vue/no-ref-as-operand
  56. value = computed(() => {
  57. return i18n.t(
  58. node.store[propName].value as string,
  59. ...(node.props.labelPlaceholder || []),
  60. )
  61. })
  62. } else {
  63. // eslint-disable-next-line vue/no-ref-as-operand
  64. value = computed(() => {
  65. return i18n.t(node.store[propName].value as string)
  66. })
  67. }
  68. }
  69. return next({ prop, value })
  70. })
  71. // Trigger hooks for props that were already set (at the moment more a hack, will be improvd in FormKit).
  72. node.on('created', () => {
  73. propsToTranslate.forEach((prop) => {
  74. if (prop in node.props) {
  75. // eslint-disable-next-line no-self-assign
  76. node.props[prop] = node.props[prop]
  77. }
  78. })
  79. })
  80. }
  81. export default translateWrapperProps