-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathuseCreateInternalUseTranslationsObjFunction.ts
More file actions
203 lines (199 loc) · 7 KB
/
useCreateInternalUseTranslationsObjFunction.ts
File metadata and controls
203 lines (199 loc) · 7 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import { useCallback } from 'react';
import { TranslateIcuCallback } from '../../../types/runtime';
import {
Dictionary,
DictionaryTranslationOptions,
TranslatedChildren,
Translations,
} from '../../../types/types';
import {
createEmptyIdError,
createNoEntryFoundWarning,
} from '../../../errors/createErrors';
import {
getSubtree,
getSubtreeWithCreation,
} from '../../../dictionaries/getSubtree';
import { isDictionaryEntry } from '../../../dictionaries/isDictionaryEntry';
import { stripMetadataFromEntries } from '../../../dictionaries/stripMetadataFromEntries';
import mergeDictionaries from '../../../dictionaries/mergeDictionaries';
import { mergeResultsIntoDictionary } from '../../../dictionaries/injectEntry';
import { injectHashes } from '../../../dictionaries/injectHashes';
import { collectUntranslatedEntries } from '../../../dictionaries/collectUntranslatedEntries';
import { injectTranslations } from '../../../dictionaries/injectTranslations';
import { injectFallbacks } from '../../../dictionaries/injectFallbacks';
import { injectAndMerge } from '../../../dictionaries/injectAndMerge';
export function useCreateInternalUseTranslationsObjFunction(
dictionary: Dictionary,
dictionaryTranslations: Dictionary,
setDictionary: Function,
setDictionaryTranslations: Function,
translations: Translations | null,
locale: string,
defaultLocale: string,
translationRequired: boolean,
dialectTranslationRequired: boolean,
developmentApiEnabled: boolean,
registerIcuForTranslation: TranslateIcuCallback,
tFunction: (id: string, options: DictionaryTranslationOptions) => string
) {
[
dictionary,
translations,
locale,
defaultLocale,
translationRequired,
dialectTranslationRequired,
developmentApiEnabled,
registerIcuForTranslation,
dictionaryTranslations,
];
return useCallback(
(
id: string,
idWithParent: string,
options: DictionaryTranslationOptions = {}
): any => {
if (idWithParent === '') {
throw new Error(createEmptyIdError());
}
// (1) Get subtree
const subtree = getSubtree({
dictionary,
id: idWithParent,
});
// Check: no subtree found
if (!subtree) {
console.warn(createNoEntryFoundWarning(idWithParent));
return {};
}
// Check: if subTreeTranslation is a dictionaryEntry
if (isDictionaryEntry(subtree)) {
return tFunction(id, options);
}
// Check: if is default locale
if (!translationRequired) {
// remove metadata from entries
return stripMetadataFromEntries(subtree);
}
const translatedSubtree = getSubtreeWithCreation({
dictionary: dictionaryTranslations,
id: idWithParent,
sourceDictionary: dictionaryTranslations,
});
// (2) Calculate subtreeWithHashes, dictionaryTranslationsWithTranslations, translatedSubtreeWithFallbacks, and untranslatedEntries
// Note: the following four operations can technically be combined into one traversal, but this
// strategy is much more readable and much easier to test/debug
// Inject hashes into subtree
const { dictionary: subtreeWithHashes, updateDictionary } = injectHashes(
// eslint-disable-next-line no-undef
structuredClone(subtree) as Dictionary,
idWithParent
);
// Collect untranslated entries
const untranslatedEntries = collectUntranslatedEntries(
subtreeWithHashes as Dictionary,
translatedSubtree as Dictionary,
idWithParent
);
// Inject translations into translation subtree
const {
dictionary: dictionaryTranslationsWithTranslations,
updateDictionary: updateDictionaryTranslations,
} = injectTranslations(
subtreeWithHashes as Dictionary,
// eslint-disable-next-line no-undef
structuredClone(translatedSubtree) as Dictionary,
translations || {},
untranslatedEntries,
idWithParent
);
// Inject fallbacks into translation subtree
const translatedSubtreeWithFallbacks = injectFallbacks(
subtreeWithHashes as Dictionary,
// eslint-disable-next-line no-undef
structuredClone(dictionaryTranslationsWithTranslations) as Dictionary,
untranslatedEntries,
idWithParent
);
// (3) For each untranslated entry, translate it
if (developmentApiEnabled) {
Promise.allSettled(
untranslatedEntries.map(
async (
untranslatedEntry
): Promise<[string, TranslatedChildren | null]> => {
const { source, metadata } = untranslatedEntry;
const id = metadata?.$id;
if (typeof source !== 'string') {
return [id, source];
}
return [
id,
await registerIcuForTranslation({
source,
targetLocale: locale,
metadata: {
...(metadata?.$context && { context: metadata.$context }),
id,
hash: metadata?.$_hash,
},
}),
];
}
)
).then((settledResults) => {
// Filter out only successful promises and extract their values
const successfulResults: [string, TranslatedChildren][] =
settledResults
.filter(
(
result
): result is PromiseFulfilledResult<
[string, TranslatedChildren]
> => result.status === 'fulfilled'
)
.map((result) => result.value);
// Only proceed if we have successful results
if (successfulResults.length > 0) {
// Merge the results into the dictionaryTranslations object
setDictionaryTranslations((prev: Dictionary) =>
mergeResultsIntoDictionary(prev, successfulResults, dictionary)
);
}
});
}
// (4) Update the dictionaryTranslations object and dictionary
// inject translatedSubtreeWithFallbacks and new subtree objects
// Need the setTimeout to avoid render-phase updates
if (updateDictionary) {
setTimeout(() => {
setDictionary((prev: Dictionary) =>
injectAndMerge(prev, subtreeWithHashes, idWithParent)
);
}, 0);
}
if (updateDictionaryTranslations) {
setTimeout(() => {
setDictionaryTranslations((prev: Dictionary) =>
mergeDictionaries(prev, dictionaryTranslationsWithTranslations)
);
}, 0);
}
// (5) Copy the dictionaryTranslations object
// eslint-disable-next-line no-undef
return structuredClone(translatedSubtreeWithFallbacks);
},
[
dictionary,
translations,
locale,
defaultLocale,
translationRequired,
dialectTranslationRequired,
developmentApiEnabled,
registerIcuForTranslation,
dictionaryTranslations,
]
);
}