forked from common-voice/common-voice
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This commit sets up a new hook that can be used to fetch a list of sorted locales. The list is sorted based on the name of each locale, localized for the current locale of the client.
- Loading branch information
1 parent
69c3cb0
commit fab0c92
Showing
2 changed files
with
42 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import {WithLocalizationProps} from '@fluent/react'; | ||
import {useLocale} from "../components/locale-helpers"; | ||
import {useMemo} from "react"; | ||
|
||
/** | ||
* An object describing a locale and its localized name. | ||
*/ | ||
interface LocalizedLocale { | ||
locale: string | ||
localizedName: string | ||
} | ||
|
||
/** | ||
* This hook provides a sorted list of locales and their localized names. | ||
* | ||
* @param {string[]} locales A list of locales to sort by localized name. | ||
* @param {function} getString A function that translates a locale to its localized name. | ||
* | ||
* @return {[string[], LocalizedLocale[]]} A tuple with both a simple, sorted array of locales, and an array of locales with their localized names. | ||
*/ | ||
function useSortedLocales( | ||
locales: string[], | ||
getString: WithLocalizationProps['getString'] | ||
): [locales: string[], localizedLocales: LocalizedLocale[]] { | ||
const [clientLocale] = useLocale(); | ||
|
||
// Memoize the array of locales and only recompute when necessary. | ||
const sortedLocales: LocalizedLocale[] = useMemo(() => locales | ||
.map(locale => ({ | ||
locale, | ||
localizedName: getString(locale).toLocaleLowerCase(clientLocale) | ||
})) | ||
.sort(({localizedName: a}, {localizedName: b}) => a.localeCompare(b, clientLocale)), | ||
[locales, clientLocale, getString] | ||
); | ||
|
||
return [sortedLocales.map(({locale}) => locale), sortedLocales] | ||
} | ||
|
||
export default useSortedLocales |