Skip to content

Commit

Permalink
common-voice#3295: Add useSortedLocales hook; Specify getString type
Browse files Browse the repository at this point in the history
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
ChristianMMacy committed Oct 19, 2021
1 parent 69c3cb0 commit fab0c92
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
3 changes: 2 additions & 1 deletion web/src/components/pages/datasets/types.ts
Expand Up @@ -2,14 +2,15 @@ import { UserClient } from 'common';
import API from '../../../services/api';
import { Notifications } from '../../../stores/notifications';
import StateTree from '../../../stores/tree';
import {WithLocalizationProps} from "@fluent/react";

//Datasets-info interfaces
export interface DatasetPropsFromState {
api: API;
}

export interface CorpusProps extends DatasetPropsFromState {
getString: Function;
getString: WithLocalizationProps['getString'];
releaseName: string;
}

Expand Down
40 changes: 40 additions & 0 deletions web/src/hooks/use-sorted-locales.ts
@@ -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

0 comments on commit fab0c92

Please sign in to comment.