aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/i18n/I18nStore.ts
blob: 4c773229f17b4921426443110e2273c3a0a8a791 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*
 * Copyright (C)  2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import type { i18n, ResourceKey, TFunction } from 'i18next';
import { IAtom, createAtom } from 'mobx';

import getLogger from '../utils/getLogger.js';

const log = getLogger('I18nStore');

export type UseTranslationResult =
  | { ready: true; i18n: i18n; t: TFunction }
  | { ready: false };

export default class I18nStore {
  private readonly languageChangedAtom: IAtom;

  private readonly namespaceLoadedAtoms: Map<string, IAtom> = new Map();

  private readonly notifyLanguageChange = () =>
    this.languageChangedAtom.reportObserved();

  constructor(private readonly i18next: i18n) {
    this.languageChangedAtom = createAtom(
      'i18next',
      () => i18next.on('languageChanged', this.notifyLanguageChange),
      () => i18next.off('languageChanged', this.notifyLanguageChange),
    );
  }

  useTranslation(ns?: string): UseTranslationResult {
    const observed = this.languageChangedAtom.reportObserved();
    const namespaceToLoad =
      ns ?? this.i18next.options.defaultNS ?? 'translation';
    if (
      this.i18next.isInitialized &&
      this.i18next.hasLoadedNamespace(namespaceToLoad)
    ) {
      return {
        ready: true,
        i18n: this.i18next,
        // eslint-disable-next-line unicorn/no-null -- `i18next` API requires `null`.
        t: this.i18next.getFixedT(null, namespaceToLoad),
      };
    }
    if (observed) {
      this.loadNamespace(namespaceToLoad);
    }
    return { ready: false };
  }

  private loadNamespace(ns: string): void {
    const existingAtom = this.namespaceLoadedAtoms.get(ns);
    if (existingAtom !== undefined) {
      existingAtom.reportObserved();
      return;
    }
    const atom = createAtom(`i18next-${ns}`);
    this.namespaceLoadedAtoms.set(ns, atom);
    atom.reportObserved();

    const loaded = () => {
      this.namespaceLoadedAtoms.delete(ns);
      atom.reportChanged();
    };

    const loadAsync = async () => {
      try {
        await this.i18next.loadNamespaces([ns]);
      } catch (error) {
        setImmediate(loaded);
        throw error;
      }
      if (this.i18next.isInitialized) {
        setImmediate(loaded);
        return;
      }
      const initialized = () => {
        setImmediate(() => {
          this.i18next.off('initialized', initialized);
          loaded();
        });
      };
      this.i18next.on('initialized', initialized);
    };

    loadAsync().catch((error) => {
      log.error('Failed to load translations for namespace', ns, error);
    });
  }

  async reloadTranslations(): Promise<void> {
    await this.i18next.reloadResources();
    setImmediate(() => {
      this.languageChangedAtom.reportChanged();
    });
    log.debug('Reloaded translations');
  }

  async getTranslation(
    language: string,
    namespace: string,
  ): Promise<ResourceKey> {
    if (!this.i18next.hasResourceBundle(language, namespace)) {
      await this.i18next.loadLanguages([language]);
      await this.i18next.loadNamespaces([namespace]);
    }
    const bundle = this.i18next.getResourceBundle(
      language,
      namespace,
    ) as unknown;
    if (typeof bundle !== 'object' || bundle === null) {
      throw new Error(
        `Failed to load ${namespace} resource bundle for language ${language}`,
      );
    }
    return bundle as ResourceKey;
  }

  addMissingTranslation(
    languages: string[],
    namespace: string,
    key: string,
    value: string,
  ): void {
    this.i18next.modules.backend?.create?.(languages, namespace, key, value);
  }
}