index.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 type { TranslationMap } from './translator.ts'
  5. import { Translator } from './translator.ts'
  6. import * as dates from './dates.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. timeFormat() {
  30. const datetimeFormat = dates.getDateTimeFormat(this.translator)
  31. const time24hour = !datetimeFormat.includes('P') // P means AM/PM
  32. return time24hour ? '24hour' : '12hour'
  33. }
  34. relativeDateTime(dateTimeString: string, baseDate?: Date): string {
  35. return dates.relativeDateTime(
  36. dateTimeString,
  37. baseDate || reactiveNow.value,
  38. this.translator,
  39. )
  40. }
  41. setTranslationMap(map: TranslationMap): void {
  42. this.translator.setTranslationMap(map)
  43. }
  44. }
  45. export const i18n = reactive(new I18N()) as I18N
  46. declare module '@vue/runtime-core' {
  47. export interface ComponentCustomProperties {
  48. i18n: I18N
  49. $t: I18N['t']
  50. __(source: string): string
  51. }
  52. }