forked from sillsdev/EthnoLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLanguageChooser.ts
More file actions
308 lines (281 loc) · 10.1 KB
/
Copy pathuseLanguageChooser.ts
File metadata and controls
308 lines (281 loc) · 10.1 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import {
ILanguage,
IScript,
isRTLScript,
asyncSearchForLanguage,
ICustomizableLanguageDetails,
deepStripDemarcation,
} from "@ethnolib/find-language";
import { useEffect, useRef, useState } from "react";
import {
isValidBcp47Tag,
isManuallyEnteredTagLanguage,
isUnlistedLanguage,
languageForManuallyEnteredTag,
parseLangtagFromLangChooser,
UNLISTED_LANGUAGE,
IOrthography,
createTagFromOrthography,
defaultDisplayName,
formatDialectCode,
} from "@ethnolib/find-language";
export interface ILanguageChooser {
languageResults: ILanguage[];
selectedLanguage: ILanguage | undefined;
selectedScript: IScript | undefined;
customizableLanguageDetails: ICustomizableLanguageDetails;
searchString: string;
onSearchStringChange: (searchString: string) => void;
selectLanguage: (language: ILanguage) => void;
selectUnlistedLanguage: () => void;
selectManuallyEnteredTagLanguage: (manuallyEnteredTag: string) => void;
clearLanguageSelection: () => void;
selectScript: (script: IScript) => void;
clearScriptSelection: () => void;
readyToSubmit: boolean;
saveLanguageDetails: (
details: ICustomizableLanguageDetails,
script: IScript | undefined
) => void;
resetTo: (
searchString?: string,
selectionLanguageTag?: string,
initialCustomDisplayName?: string
) => void;
}
export const useLanguageChooser = (
onSelectionChange?: (
orthography: IOrthography | undefined,
langtag: string | undefined
) => void,
searchResultModifier?: (
results: ILanguage[],
searchString: string
) => ILanguage[]
) => {
const [searchString, setSearchString] = useState<string>("");
// we use useRef to help with asynchronously accessing the up-to-date value from the search function -
// if the user keeps typing we want to cancel the previous searches promptly and the searchString won't have updated yet
// But we still need the searchString state to trigger the useEffect
const searchStringRef = useRef("");
const [selectedLanguage, setSelectedLanguage] = useState<
ILanguage | undefined
>();
const [selectedScript, setSelectedScript] = useState<IScript | undefined>();
const EMPTY_CUSTOMIZABLE_LANGUAGE_DETAILS = {
customDisplayName: undefined,
region: undefined,
dialect: undefined,
} as ICustomizableLanguageDetails;
const [customizableLanguageDetails, setCustomizableLanguageDetails] =
useState<ICustomizableLanguageDetails>(EMPTY_CUSTOMIZABLE_LANGUAGE_DETAILS);
function clearCustomizableLanguageDetails() {
setCustomizableLanguageDetails(EMPTY_CUSTOMIZABLE_LANGUAGE_DETAILS);
}
const readyToSubmit = isReadyToSubmit({
language: selectedLanguage,
script: selectedScript,
customDetails: customizableLanguageDetails,
});
const [languageResults, setLanguageResults] = useState<ILanguage[]>([]);
// For faster results, the search function returns better results first but then continues searching for more results
// and appends them to the result list, in several rounds.
// Return true if we should continue searching for more results, and false if we should abort because the search string has changed
function appendResults(
additionalSearchResults: ILanguage[],
forSearchString: string
) {
if (forSearchString !== searchStringRef.current) {
// Search string has changed, stop looking for results for this search string
return false;
}
const modifier = searchResultModifier || ((r) => r);
//append the new results to the existing results
setLanguageResults((r) =>
r.concat(modifier(additionalSearchResults, forSearchString))
);
return true; // Keep looking for more results
}
useEffect(() => {
setLanguageResults([]);
if (!searchString || searchString.length < 2) {
return;
}
(async () => {
await asyncSearchForLanguage(searchString, appendResults);
})();
}, [searchString]);
// For reopening to a specific selection
function resetTo(
searchString?: string,
selectionLanguageTag?: string,
initialCustomDisplayName?: string // all info can be captured in language tag except display name
) {
if (!selectionLanguageTag) {
onSearchStringChange(searchString || "");
return;
}
let initialSelections = parseLangtagFromLangChooser(
selectionLanguageTag || "",
searchResultModifier
);
if (selectionLanguageTag && !initialSelections) {
// we failed to parse the tag, meaning this is a langtag requiring manual entry
initialSelections = {
language: languageForManuallyEnteredTag(selectionLanguageTag || ""),
script: undefined,
customDetails: {
customDisplayName: initialCustomDisplayName,
},
};
}
// If we have an initially selected language but no search string, might as well set the search string to something
// that will definitely show that selected language in the results
searchString = searchString || initialSelections?.language?.languageSubtag;
onSearchStringChange(searchString || "");
if (initialSelections?.language) {
selectLanguage(initialSelections?.language as ILanguage);
}
if (initialSelections?.script) {
selectScript(initialSelections.script);
}
setCustomizableLanguageDetails({
...(initialSelections?.customDetails ||
({} as ICustomizableLanguageDetails)),
// we only save the custom display name if it is different from the default
customDisplayName:
initialCustomDisplayName &&
initialCustomDisplayName !==
defaultDisplayName(
initialSelections?.language,
initialSelections?.script
)
? initialCustomDisplayName
: undefined,
});
}
function saveLanguageDetails(
details: ICustomizableLanguageDetails,
script: IScript | undefined
) {
setCustomizableLanguageDetails(details);
// If the provided script is empty but this language only has one script, automatically go back to that implied script
if (!script && selectedLanguage?.scripts.length === 1) {
script = selectedLanguage.scripts[0];
}
setSelectedScript(script);
}
function selectLanguage(language: ILanguage) {
setSelectedLanguage(language);
setSelectedScript(
// If there is only one script option for this language, automatically select it
language.scripts.length === 1 ? language.scripts[0] : undefined
);
clearCustomizableLanguageDetails();
}
function selectUnlistedLanguage() {
selectLanguage(UNLISTED_LANGUAGE);
}
function selectManuallyEnteredTagLanguage(manuallyEnteredTag: string) {
selectLanguage(languageForManuallyEnteredTag(manuallyEnteredTag));
}
function clearLanguageSelection() {
setSelectedLanguage(undefined);
setSelectedScript(undefined);
clearCustomizableLanguageDetails();
}
function clearCustomizableDetailsExceptDisplayName() {
setCustomizableLanguageDetails((d) => ({
...EMPTY_CUSTOMIZABLE_LANGUAGE_DETAILS,
customDisplayName: d.customDisplayName,
}));
}
function selectScript(script: IScript) {
setSelectedScript(script);
clearCustomizableDetailsExceptDisplayName(); // BL-15918
}
function clearScriptSelection() {
setSelectedScript(undefined);
clearCustomizableDetailsExceptDisplayName(); // BL-15918
}
function onSearchStringChange(newSearchString: string) {
searchStringRef.current = newSearchString;
setSearchString(newSearchString);
setSelectedLanguage(undefined);
setSelectedScript(undefined);
clearCustomizableLanguageDetails();
}
const [previousStateWasValidSelection, setPreviousStateWasValidSelection] =
useState(false);
useEffect(() => {
if (onSelectionChange) {
if (readyToSubmit) {
const resultingOrthography = deepStripDemarcation({
language: selectedLanguage,
script: selectedScript,
customDetails: customizableLanguageDetails,
}) as IOrthography;
if (resultingOrthography.script) {
resultingOrthography.script.isRtl = isRTLScript(
resultingOrthography.script.code
);
}
const tag = createTagFromOrthography(resultingOrthography);
onSelectionChange(resultingOrthography, tag);
setPreviousStateWasValidSelection(true);
} else if (previousStateWasValidSelection) {
onSelectionChange(undefined, undefined);
setPreviousStateWasValidSelection(false);
}
}
}, [selectedLanguage, selectedScript, customizableLanguageDetails]);
return {
languageResults,
selectedLanguage,
selectedScript,
customizableLanguageDetails,
searchString: searchString,
onSearchStringChange,
selectLanguage,
selectUnlistedLanguage,
selectManuallyEnteredTagLanguage,
clearLanguageSelection,
selectScript,
clearScriptSelection,
readyToSubmit,
saveLanguageDetails,
resetTo,
} as ILanguageChooser;
};
function hasValidDisplayName(selection: IOrthography) {
if (!selection.language) {
return false;
}
// Check that user has not entered an empty string or whitespace only in the custom display name
if (
typeof selection.customDetails?.customDisplayName === "string" &&
!selection.customDetails?.customDisplayName?.trim()
) {
return false;
}
// Check that we have a default display name and/or a custom display name
return (
!!defaultDisplayName(selection.language, selection.script) ||
!!selection.customDetails?.customDisplayName
);
}
export function isReadyToSubmit(selection: IOrthography): boolean {
const normalizedDialect = formatDialectCode(selection.customDetails?.dialect);
return (
!!selection.language &&
hasValidDisplayName(selection) &&
// either a script is selected or there are no scripts for the selected language
(!!selection.script || selection.language?.scripts?.length === 0) &&
// if unlisted language, name and country are required
(!isUnlistedLanguage(selection.language) ||
(!!normalizedDialect && !!selection.customDetails?.region?.name)) &&
// if this was a manually entered langtag, check that tag is valid BCP 47
(!isManuallyEnteredTagLanguage(selection.language) ||
isValidBcp47Tag(selection.language?.manuallyEnteredTag))
);
}