akkoma/lib/pleroma/web/gettext.ex
Tusooa Zhu ef73f61b07 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.
2022-06-29 20:47:10 +01:00

81 lines
2.1 KiB
Elixir

# Pleroma: A lightweight social networking server
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
defmodule Pleroma.Web.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import Pleroma.Web.Gettext
# Simple translation
gettext "Here is the string to translate"
# Plural translation
ngettext "Here is the string to translate",
"Here are the strings to translate",
3
# Domain-based translation
dgettext "errors", "Here is the error message to translate"
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :pleroma
def language_tag do
# Naive implementation: HTML lang attribute uses BCP 47, which
# uses - as a separator.
# https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
Gettext.get_locale()
|> String.replace("_", "-", global: true)
end
def normalize_locale(locale) do
if is_binary(locale) do
String.replace(locale, "-", "_")
else
nil
end
end
def supports_locale?(locale) do
Pleroma.Web.Gettext
|> Gettext.known_locales()
|> 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
else
Gettext.get_locale()
end
end
defmacro with_locale_or_default(locale, do: fun) do
quote do
Gettext.with_locale(Pleroma.Web.Gettext.locale_or_default(unquote(locale)), fn ->
unquote(fun)
end)
end
end
end