aboutsummaryrefslogtreecommitdiffstats
path: root/packages/renderer/src/i18n/RendererIpcI18nBackend.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/renderer/src/i18n/RendererIpcI18nBackend.ts')
-rw-r--r--packages/renderer/src/i18n/RendererIpcI18nBackend.ts75
1 files changed, 75 insertions, 0 deletions
diff --git a/packages/renderer/src/i18n/RendererIpcI18nBackend.ts b/packages/renderer/src/i18n/RendererIpcI18nBackend.ts
new file mode 100644
index 0000000..13e03b5
--- /dev/null
+++ b/packages/renderer/src/i18n/RendererIpcI18nBackend.ts
@@ -0,0 +1,75 @@
1/*
2 * Copyright (C) 2022 Kristóf Marussy <kristof@marussy.com>
3 *
4 * This file is part of Sophie.
5 *
6 * Sophie is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, version 3.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: AGPL-3.0-only
19 */
20
21import { SophieRenderer } from '@sophie/shared';
22import type { BackendModule, ReadCallback } from 'i18next';
23
24export default class RendererIpcI18nBackend implements BackendModule<unknown> {
25 type = 'backend' as const;
26
27 constructor(
28 private readonly ipc: SophieRenderer,
29 private readonly devMode = false,
30 ) {}
31
32 // eslint-disable-next-line class-methods-use-this -- Method required by interface.
33 init() {}
34
35 read(language: string, namespace: string, callback: ReadCallback): void {
36 const readAsync = async () => {
37 const translations = await this.ipc.getTranslation({
38 language,
39 namespace,
40 });
41 // eslint-disable-next-line unicorn/no-null -- `i18next` API requires `null`.
42 setTimeout(() => callback(null, translations), 0);
43 };
44
45 readAsync().catch((error) => {
46 const callbackError =
47 error instanceof Error
48 ? error
49 : new Error(`Unknown error: ${JSON.stringify(error)}`);
50 /*
51 eslint-disable-next-line promise/no-callback-in-promise, unicorn/no-null --
52 Converting from promise based API to a callback. `i18next` API requires `null`.
53 */
54 setTimeout(() => callback(callbackError, null), 0);
55 });
56 }
57
58 create(
59 languages: string[],
60 namespace: string,
61 key: string,
62 fallbackValue: string,
63 ): void {
64 if (!this.devMode) {
65 throw new Error('Refusing to add missing translation in production mode');
66 }
67 this.ipc.dispatchAction({
68 action: 'add-missing-translation',
69 languages,
70 namespace,
71 key,
72 value: fallbackValue,
73 });
74 }
75}