aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/i18n/I18nStore.ts
blob: d833e8a1062476e5f76c800dadfbc3f4564dcad2 (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
/*
 * 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, TFunction } from 'i18next';
import { IAtom, createAtom } from 'mobx';

import { getLogger } from '../utils/log';

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 () => {
      await this.i18next.loadNamespaces([ns]);
      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);
      setImmediate(loaded);
    });
  }
}