i18nUtils.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import type { VueI18n } from 'vue-i18n'
  2. import type { CountryCode } from 'libphonenumber-js'
  3. import { parsePhoneNumber } from 'libphonenumber-js'
  4. import type { EnumChoice, EnumChoices } from '~/types/interfaces'
  5. import ArrayUtils from '~/services/utils/arrayUtils'
  6. import type { ResourceTreeContent } from '~/types/data'
  7. export default class I18nUtils {
  8. private i18n!: VueI18n
  9. public constructor(i18n: VueI18n) {
  10. this.i18n = i18n
  11. }
  12. /**
  13. * Return the given enum with its labels translated
  14. *
  15. * If sort is true, the enum is also sorted by its newly translated labels
  16. *
  17. * @param enum_
  18. * @param sort
  19. */
  20. public translateEnum(enum_: EnumChoices, sort: boolean = true): EnumChoices {
  21. enum_ = enum_.map((item: EnumChoice) => {
  22. return { value: item.value, label: this.i18n.t(item.label) as string }
  23. })
  24. if (sort) {
  25. // @ts-expect-error enum_ is now an array of EnumChoice
  26. enum_ = ArrayUtils.sortObjectsByProp(enum_, 'label') as EnumChoices
  27. }
  28. return enum_
  29. }
  30. public formatPhoneNumber(
  31. number: string,
  32. defaultCountry?: CountryCode,
  33. ): string {
  34. const parsed = parsePhoneNumber(number, defaultCountry)
  35. return parsed ? parsed.formatNational() : ''
  36. }
  37. /**
  38. * Translate the different levels of a resource tree's content
  39. * @param tree
  40. */
  41. public translateResourceTree(tree: ResourceTreeContent): ResourceTreeContent {
  42. if (Array.isArray(tree)) {
  43. return tree.map(item => this.i18n.t(item))
  44. }
  45. const translatedTree: ResourceTreeContent = {}
  46. for (const key in tree) {
  47. const value = tree[key]
  48. const translatedKey = this.i18n.t(key)
  49. // @ts-expect-error Nécessaire pour la récursion
  50. translatedTree[translatedKey] = this.translateResourceTree(value)
  51. }
  52. return translatedTree
  53. }
  54. }