index.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { reactive } from 'vue'
  3. import { useReactiveNow } from '#shared/composables/useReactiveNow.ts'
  4. import * as dates from './dates.ts'
  5. import { Translator } from './translator.ts'
  6. import type { TranslationMap } from './translator.ts'
  7. const reactiveNow = useReactiveNow()
  8. export class I18N {
  9. private translator = new Translator()
  10. t(
  11. source: string | undefined,
  12. ...args: Array<string | number | undefined | null | boolean>
  13. ): string {
  14. if (typeof source === 'undefined') return ''
  15. return this.translator.translate(source, ...args)
  16. }
  17. // eslint-disable-next-line class-methods-use-this
  18. locale() {
  19. return document.documentElement.getAttribute('lang') || 'en-US'
  20. }
  21. date(dateString: string): string {
  22. const template = dates.getDateFormat(this.translator)
  23. return dates.absoluteDateTime(dateString, template)
  24. }
  25. dateTime(dateTimeString: string): string {
  26. const template = dates.getDateTimeFormat(this.translator)
  27. return dates.absoluteDateTime(dateTimeString, template)
  28. }
  29. relativeDateTime(dateTimeString: string, baseDate?: Date): string {
  30. return dates.relativeDateTime(
  31. dateTimeString,
  32. baseDate || reactiveNow.value,
  33. this.translator,
  34. )
  35. }
  36. setTranslationMap(map: TranslationMap): void {
  37. this.translator.setTranslationMap(map)
  38. }
  39. getDateFormat(): string {
  40. return dates.getDateFormat(this.translator)
  41. }
  42. getDateTimeFormat(): string {
  43. return dates.getDateTimeFormat(this.translator)
  44. }
  45. getTimeFormatType() {
  46. const time24hour = !this.getDateTimeFormat().includes('P') // P means AM/PM
  47. return time24hour ? '24hour' : '12hour'
  48. }
  49. }
  50. export const i18n = reactive(new I18N()) as I18N
  51. declare module '@vue/runtime-core' {
  52. export interface ComponentCustomProperties {
  53. i18n: I18N
  54. $t: I18N['t']
  55. __(source: string): string
  56. }
  57. }