2021-06-21 21:11:53 +01:00
|
|
|
import { IntlContext, translate } from "preact-i18n";
|
2021-06-20 17:31:53 +01:00
|
|
|
import { useContext } from "preact/hooks";
|
2021-07-05 11:23:23 +01:00
|
|
|
|
2021-08-04 14:31:55 +01:00
|
|
|
import { Dictionary } from "../context/Locale";
|
|
|
|
|
2021-06-20 17:31:53 +01:00
|
|
|
interface Fields {
|
2021-07-05 11:25:20 +01:00
|
|
|
[key: string]: Children;
|
2021-06-20 17:31:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
interface Props {
|
2021-07-05 11:25:20 +01:00
|
|
|
id: string;
|
|
|
|
fields: Fields;
|
2021-06-20 17:31:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export interface IntlType {
|
2021-07-05 11:25:20 +01:00
|
|
|
intl: {
|
2021-07-06 19:29:09 +01:00
|
|
|
dictionary: Dictionary;
|
2021-07-05 11:25:20 +01:00
|
|
|
};
|
2021-06-20 17:31:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// This will exhibit O(2^n) behaviour.
|
|
|
|
function recursiveReplaceFields(input: string, fields: Fields) {
|
2021-07-05 11:25:20 +01:00
|
|
|
const key = Object.keys(fields)[0];
|
|
|
|
if (key) {
|
|
|
|
const { [key]: field, ...restOfFields } = fields;
|
|
|
|
if (typeof field === "undefined") return [input];
|
|
|
|
|
|
|
|
const values: (Children | string[])[] = input
|
|
|
|
.split(`{{${key}}}`)
|
|
|
|
.map((v) => recursiveReplaceFields(v, restOfFields));
|
|
|
|
|
|
|
|
for (let i = values.length - 1; i > 0; i -= 2) {
|
|
|
|
values.splice(i, 0, field);
|
|
|
|
}
|
|
|
|
|
|
|
|
return values.flat();
|
|
|
|
}
|
2021-07-10 15:57:29 +01:00
|
|
|
// base case
|
|
|
|
return [input];
|
2021-06-20 17:31:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export function TextReact({ id, fields }: Props) {
|
2021-07-05 11:25:20 +01:00
|
|
|
const { intl } = useContext(IntlContext) as unknown as IntlType;
|
2021-06-20 17:31:53 +01:00
|
|
|
|
2021-07-05 11:25:20 +01:00
|
|
|
const path = id.split(".");
|
|
|
|
let entry = intl.dictionary[path.shift()!];
|
2021-07-10 15:57:29 +01:00
|
|
|
for (const key of path) {
|
2021-08-05 14:47:00 +01:00
|
|
|
// @ts-expect-error TODO: lazy
|
2021-07-05 11:25:20 +01:00
|
|
|
entry = entry[key];
|
|
|
|
}
|
2021-06-20 17:31:53 +01:00
|
|
|
|
2021-07-05 11:25:20 +01:00
|
|
|
return <>{recursiveReplaceFields(entry as string, fields)}</>;
|
2021-06-20 17:31:53 +01:00
|
|
|
}
|
2021-06-21 21:11:53 +01:00
|
|
|
|
|
|
|
export function useTranslation() {
|
2021-07-05 11:25:20 +01:00
|
|
|
const { intl } = useContext(IntlContext) as unknown as IntlType;
|
2021-08-05 14:47:00 +01:00
|
|
|
return (
|
|
|
|
id: string,
|
|
|
|
fields?: Record<string, string | undefined>,
|
|
|
|
plural?: number,
|
|
|
|
fallback?: string,
|
|
|
|
) => translate(id, "", intl.dictionary, fields, plural, fallback);
|
2021-06-21 21:11:53 +01:00
|
|
|
}
|
2021-07-06 19:29:09 +01:00
|
|
|
|
|
|
|
export function useDictionary() {
|
|
|
|
const { intl } = useContext(IntlContext) as unknown as IntlType;
|
|
|
|
return intl.dictionary;
|
|
|
|
}
|