keycloak_theme/src/lib/i18n/useKcTranslation.tsx

43 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-03-02 23:48:31 +01:00
import { useKcLanguageTag } from "./useKcLanguageTag";
import { messages } from "./generated_messages/login";
import { useConstCallback } from "powerhooks";
2021-03-01 20:45:37 +01:00
import type { ReactNode } from "react";
2021-03-02 22:48:36 +01:00
import { id } from "evt/tools/typeSafety/id";
2021-03-02 22:48:36 +01:00
export type MessageKey = keyof typeof messages["en"];
2021-03-02 23:48:31 +01:00
export function useKcTranslation() {
2021-03-02 23:48:31 +01:00
const { kcLanguageTag } = useKcLanguageTag();
2021-03-02 22:48:36 +01:00
const tStr = useConstCallback(
(key: MessageKey, ...args: (string | undefined)[]): string => {
2021-03-02 23:48:31 +01:00
let str: string = messages[kcLanguageTag as any as "en"][key] ?? messages["en"][key];
2021-03-01 20:45:37 +01:00
args.forEach((arg, i) => {
if (arg === undefined) {
return;
}
2021-03-02 22:48:36 +01:00
str = str.replace(new RegExp(`\\{${i}\\}`, "g"), arg);
2021-03-01 20:45:37 +01:00
});
2021-03-02 22:48:36 +01:00
return str;
}
);
2021-03-02 22:48:36 +01:00
const t = useConstCallback(
id<(...args: Parameters<typeof tStr>) => ReactNode>(
(key, ...args) =>
<span className={key} dangerouslySetInnerHTML={{ "__html": tStr(key, ...args) }} />
)
);
return { t, tStr };
}