index.ts 1.7 KB

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