index.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. dateTimeISO(dateTimeString: string): string {
  30. return dates.getISODatetime(dateTimeString)
  31. }
  32. relativeDateTime(dateTimeString: string, baseDate?: Date): string {
  33. return dates.relativeDateTime(
  34. dateTimeString,
  35. baseDate || reactiveNow.value,
  36. this.translator,
  37. )
  38. }
  39. setTranslationMap(map: TranslationMap): void {
  40. this.translator.setTranslationMap(map)
  41. }
  42. getDateFormat(): string {
  43. return dates.getDateFormat(this.translator)
  44. }
  45. getDateTimeFormat(): string {
  46. return dates.getDateTimeFormat(this.translator)
  47. }
  48. getTimeFormatType() {
  49. const time24hour = !this.getDateTimeFormat().includes('P') // P means AM/PM
  50. return time24hour ? '24hour' : '12hour'
  51. }
  52. }
  53. export const i18n = reactive(new I18N()) as I18N
  54. declare module '@vue/runtime-core' {
  55. export interface ComponentCustomProperties {
  56. i18n: I18N
  57. $t: I18N['t']
  58. __(source: string): string
  59. }
  60. }