Open History to see the last commit
1/** The only Chromium locale packaged builds ship, so Electron seeds the spellchecker with it. */
2const PACKAGED_DEFAULT_LANGUAGE = "en-US";
3
4const normalizeLanguageTag = (tag: string): string =>
5 tag.split(/[.@]/)[0]!.replace(/_/g, "-").toLowerCase();
6
7const baseLanguage = (tag: string): string => tag.toLowerCase().split("-")[0]!;
8
9const findExactLanguage = (tag: string, available: ReadonlyArray<string>): string | undefined =>
10 available.find((language) => language.toLowerCase() === tag);
11
12const findBaseLanguage = (base: string, available: ReadonlyArray<string>): string | undefined =>
13 available.find((language) => language.toLowerCase() === base) ??
14 available.find((language) => language.toLowerCase().startsWith(`${base}-`));
15
16/**
17 * The dictionaries to use instead of the packaged en-US default, or undefined to leave the
18 * session alone. A list other than the seeded default is the user's own choice and is kept.
19 */
20export const resolveSpellCheckerLanguages = (
21 current: ReadonlyArray<string>,
22 preferredSystemLanguages: ReadonlyArray<string>,
23 available: ReadonlyArray<string>,
24): string[] | undefined => {
25 if (current.length > 1 || (current[0] ?? PACKAGED_DEFAULT_LANGUAGE) !== PACKAGED_DEFAULT_LANGUAGE)
26 return undefined;
27 const tags = preferredSystemLanguages.map(normalizeLanguageTag);
28 // GLib follows en_GB with a generated "en", and Chromium's "en" is the en-US dictionary, so a tag
29 // without a region is only a fallback and must not add another dictionary for its language.
30 const exactMatches = tags.map((tag) =>
31 tag.includes("-") ? findExactLanguage(tag, available) : undefined,
32 );
33 const coveredBases = new Set(
34 exactMatches.flatMap((match) => (match ? [baseLanguage(match)] : [])),
35 );
36 const languages: string[] = [];
37 tags.forEach((tag, index) => {
38 let match = exactMatches[index];
39 if (!match) {
40 const base = baseLanguage(tag);
41 if (coveredBases.has(base)) return;
42 match = findBaseLanguage(base, available);
43 if (match) coveredBases.add(base);
44 }
45 if (match && !languages.includes(match)) languages.push(match);
46 });
47 if (languages.length === 0) return undefined;
48 if (languages.length === 1 && languages[0] === PACKAGED_DEFAULT_LANGUAGE) return undefined;
49 return languages;
50};