diff options
author | Tusooa Zhu <tusooa@kazv.moe> | 2022-03-02 19:59:11 -0500 |
---|---|---|
committer | Tusooa Zhu <tusooa@kazv.moe> | 2022-03-02 19:59:11 -0500 |
commit | 8de573b04783ef50b74bd629843a58b37c0ce31d (patch) | |
tree | 1c7ad235630ef24cf8ed5cfbd8a8dbfa53aac911 /lib | |
parent | 1a917cfeec3057fca9c5d1467fd9bf1401d27d42 (diff) | |
download | pleroma-8de573b04783ef50b74bd629843a58b37c0ce31d.tar.gz pleroma-8de573b04783ef50b74bd629843a58b37c0ce31d.zip |
Fallback to a variant if the language in general is not supported
For an example, here, zh is not supported, but zh_Hans and zh_Hant
are. If the user asks for zh, we should choose a variant for them
instead of fallbacking to default.
Some browsers (e.g. Firefox) does not allow users to customize
their language codes. For example, there is no zh-Hans, but only
zh, zh-CN, zh-TW, zh-HK, etc. This provides a workaround for
those users suffering from bad design decisions.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/pleroma/web/gettext.ex | 14 | ||||
-rw-r--r-- | lib/pleroma/web/plugs/set_locale_plug.ex | 6 |
2 files changed, 20 insertions, 0 deletions
diff --git a/lib/pleroma/web/gettext.ex b/lib/pleroma/web/gettext.ex index 828b98b15..cfd92f991 100644 --- a/lib/pleroma/web/gettext.ex +++ b/lib/pleroma/web/gettext.ex @@ -49,6 +49,20 @@ defmodule Pleroma.Web.Gettext do |> Enum.member?(locale) end + def variant?(locale), do: String.contains?(locale, "_") + + def supported_variants_of_locale(locale) do + cond do + variant?(locale) -> + [locale] + supports_locale?(locale) -> + [locale] + true -> + Gettext.known_locales(Pleroma.Web.Gettext) + |> Enum.filter(fn l -> String.starts_with?(l, locale <> "_") end) + end + end + def locale_or_default(locale) do if supports_locale?(locale) do locale diff --git a/lib/pleroma/web/plugs/set_locale_plug.ex b/lib/pleroma/web/plugs/set_locale_plug.ex index 4c6e44fb5..78ae566c7 100644 --- a/lib/pleroma/web/plugs/set_locale_plug.ex +++ b/lib/pleroma/web/plugs/set_locale_plug.ex @@ -20,6 +20,12 @@ defmodule Pleroma.Web.Plugs.SetLocalePlug do conn |> extract_preferred_language() |> normalize_language_codes() + |> first_supported() + end + + defp first_supported(locales) do + locales + |> Enum.flat_map(&Pleroma.Web.Gettext.supported_variants_of_locale/1) |> Enum.find(&supported_locale?/1) end |