Skip to content

Commit

Permalink
Prefer the selected language group over default
Browse files Browse the repository at this point in the history
  • Loading branch information
sarayourfriend committed Oct 9, 2020
1 parent 5bb7c13 commit a09e3ec
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion packages/language-picker/src/language-picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import React, { useState } from 'react';
import { useI18n } from '@automattic/react-i18n';
import { intersection } from 'lodash';

/**
* WordPress dependencies
Expand Down Expand Up @@ -30,6 +31,32 @@ type Props = {
localizedLanguageNames?: LocalizedLanguageNames;
};

const findBestDefaultLanguageGroupId = (
selectedLanguage: Language | undefined,
languageGroups: LanguageGroup[],
defaultLananguageGroupId: string
): string => {
if ( ! selectedLanguage ) {
return defaultLananguageGroupId;
}

if ( selectedLanguage.popular ) {
return 'popular';
}

return (
languageGroups.find( ( lg ) => {
const sharedTerritories = intersection( lg.subTerritories, selectedLanguage.territories );

if ( sharedTerritories.length > 0 ) {
return lg;
}

return false;
} )?.id ?? defaultLananguageGroupId
);
};

const LanguagePicker = ( {
onSelectLanguage,
languages,
Expand All @@ -40,7 +67,9 @@ const LanguagePicker = ( {
localizedLanguageNames,
}: Props ) => {
const { __ } = useI18n();
const [ filter, setFilter ] = useState( defaultLananguageGroupId );
const [ filter, setFilter ] = useState(
findBestDefaultLanguageGroupId( selectedLanguage, languageGroups, defaultLananguageGroupId )
);

const getFilteredLanguages = () => {
switch ( filter ) {
Expand Down

0 comments on commit a09e3ec

Please sign in to comment.