This commit is contained in:
Joseph Garrone
2021-03-01 20:45:37 +01:00
parent 57a0d9f10f
commit f599df2bb7
11 changed files with 617 additions and 158 deletions

View File

@ -3,6 +3,7 @@ import { createUseGlobalState } from "powerhooks";
import { messages } from "./generated_messages/login";
import { objectKeys } from "evt/tools/typeSafety/objectKeys";
import { getLanguageLabel } from "./getLanguageLabel";
import { keycloakPagesContext } from "../keycloakFtlValues";
const availableLanguages = objectKeys(messages);
@ -10,18 +11,21 @@ export type AvailableLanguages = typeof availableLanguages[number];
export const { useKeycloakLanguage } = createUseGlobalState(
"keycloakLanguage",
getKeycloakAvailableLanguageBestGuess,
() => getBestMatchAmongKeycloakAvailableLanguages(
keycloakPagesContext?.locale?.["current" as never] ??
navigator.language
),
{ "persistance": "cookies" }
);
/**
* Pass in "fr-FR" or "français" for example, it will return the AvailableLanguage
* it corresponds to.
* it corresponds to: "fr".
* If there is no reasonable match it's guessed from navigator.language.
* If still no matches en is returned.
* If still no matches "en" is returned.
*/
export function getKeycloakAvailableLanguageBestGuess(
languageLike: string = navigator.language
export function getBestMatchAmongKeycloakAvailableLanguages(
languageLike: string
): AvailableLanguages {
const iso2LanguageLike = languageLike.split("-")[0].toLowerCase();
@ -32,7 +36,7 @@ export function getKeycloakAvailableLanguageBestGuess(
);
if (language === undefined && languageLike !== navigator.language) {
return getKeycloakAvailableLanguageBestGuess(navigator.language);
return getBestMatchAmongKeycloakAvailableLanguages(navigator.language);
}
return "en";

View File

@ -2,7 +2,7 @@
import { useKeycloakLanguage } from "./useKeycloakLanguage";
import { messages } from "./generated_messages/login";
import { useConstCallback } from "powerhooks";
import type { ReactNode } from "react";
import type { ReactNode } from "react";
export type MessageKey = keyof typeof messages["en"]
@ -12,13 +12,19 @@ export function useKeycloakThemeTranslation() {
const { keycloakLanguage } = useKeycloakLanguage();
const t = useConstCallback(
(key: MessageKey, ...args: string[]): ReactNode => {
(key: MessageKey, ...args: (string | undefined)[]): ReactNode => {
let out: string = messages[keycloakLanguage as any as "en"][key] ?? messages["en"][key];
args.forEach((arg, i)=>
out= out.replace(new RegExp(`\\{${i}\\}`, "g"), arg)
);
args.forEach((arg, i) => {
if (arg === undefined) {
return;
}
out = out.replace(new RegExp(`\\{${i}\\}`, "g"), arg);
});
return <span className={key} dangerouslySetInnerHTML={{ "__html": out }} />;