diff --git a/src/contexts/settings.ts b/src/contexts/settings.ts index e0d15fe..2c50f7f 100644 --- a/src/contexts/settings.ts +++ b/src/contexts/settings.ts @@ -2,7 +2,7 @@ import { useRouter } from "next/router"; import { useEffect } from "react"; import { atom } from "jotai"; import { atomWithStorage } from "jotai/utils"; -import { atomPairing, useAtomGetter, useAtomPair, useAtomSetter } from "helpers/atoms"; +import { atomPairing, useAtomGetter, useAtomPair } from "helpers/atoms"; import { isDefined } from "helpers/asserts"; import { usePrefersDarkMode } from "hooks/useMediaQuery"; import { userAgent } from "contexts/userAgent"; @@ -69,7 +69,7 @@ export const settings = { export const useSettings = (): void => { const router = useRouter(); - const setPreferredLanguages = useAtomSetter(preferredLanguagesAtom); + const [preferredLanguages, setPreferredLanguages] = useAtomPair(preferredLanguagesAtom); const fontSize = useAtomGetter(fontSizeAtom); const isDyslexic = useAtomGetter(dyslexicAtom); const [isDarkMode, setDarkMode] = useAtomPair(darkModeAtom); @@ -144,5 +144,5 @@ export const useSettings = (): void => { locale: localStorageValue[0], }); } - }, [router, setPreferredLanguages]); + }, [router, setPreferredLanguages, preferredLanguages]); }; diff --git a/src/hooks/useSmartLanguage.ts b/src/hooks/useSmartLanguage.ts index 1fd1106..f15dd25 100644 --- a/src/hooks/useSmartLanguage.ts +++ b/src/hooks/useSmartLanguage.ts @@ -1,7 +1,7 @@ import { useRouter } from "next/router"; import { useEffect, useMemo, useState } from "react"; import { LanguageSwitcher } from "components/Inputs/LanguageSwitcher"; -import { filterDefined, isDefined } from "helpers/asserts"; +import { isDefined } from "helpers/asserts"; import { getPreferredLanguage } from "helpers/locales"; import { atoms } from "contexts/atoms"; import { useAtomGetter } from "helpers/atoms"; @@ -21,14 +21,18 @@ export const useSmartLanguage = ({ const languages = useAtomGetter(atoms.localData.languages); const router = useRouter(); - const availableLocales = useMemo(() => { - const memo = new Map(); - filterDefined(items).map((elem, index) => { - const result = languageExtractor(elem); - if (isDefined(result)) memo.set(result, index); + const availableLocales = useMemo>(() => { + const memo: [string, number][] = []; + items.map((elem, index) => { + const result = isDefined(elem) ? languageExtractor(elem) : undefined; + if (isDefined(result)) memo.push([result, index]); }); - return memo; - }, [items, languageExtractor]); + memo.sort((a, b) => { + const evaluate = (locale: string) => preferredLanguages.findIndex((elem) => elem === locale); + return evaluate(a[0]) - evaluate(b[0]); + }); + return new Map(memo); + }, [items, languageExtractor, preferredLanguages]); const [selectedTranslationIndex, setSelectedTranslationIndex] = useState();