2023-10-25 16:16:25 +00:00
|
|
|
import { useCallback, useMemo } from "react";
|
2023-10-25 14:58:38 +00:00
|
|
|
import { useTranslation } from "react-i18next";
|
|
|
|
|
2023-12-06 21:04:50 +00:00
|
|
|
// 10% chance of getting a joke title
|
|
|
|
const shouldGiveJokeTitle = () => Math.floor(Math.random() * 10) === 0;
|
|
|
|
|
2023-10-25 14:58:38 +00:00
|
|
|
export function useRandomTranslation() {
|
|
|
|
const { t } = useTranslation();
|
2023-10-25 16:16:25 +00:00
|
|
|
const seed = useMemo(() => Math.random(), []);
|
2023-10-25 14:58:38 +00:00
|
|
|
|
2023-10-25 16:16:25 +00:00
|
|
|
const getRandomTranslation = useCallback(
|
2023-12-06 21:04:50 +00:00
|
|
|
(key: string): string => {
|
|
|
|
const shouldRandom = shouldGiveJokeTitle();
|
|
|
|
const defaultTitle = t(`${key}.default`) ?? "";
|
|
|
|
if (!shouldRandom) return defaultTitle;
|
2023-10-25 14:58:38 +00:00
|
|
|
|
2023-12-06 21:04:50 +00:00
|
|
|
const keys = t(`${key}.extra`, { returnObjects: true });
|
|
|
|
if (Array.isArray(keys)) {
|
|
|
|
if (keys.length === 0) return defaultTitle;
|
|
|
|
return keys[Math.floor(seed * keys.length)];
|
2023-10-25 16:16:25 +00:00
|
|
|
}
|
2023-10-25 14:58:38 +00:00
|
|
|
|
2023-12-06 21:04:50 +00:00
|
|
|
return typeof keys === "string" ? keys : defaultTitle;
|
2023-10-25 16:16:25 +00:00
|
|
|
},
|
|
|
|
[t, seed]
|
|
|
|
);
|
2023-10-25 14:58:38 +00:00
|
|
|
|
|
|
|
return { t: getRandomTranslation };
|
|
|
|
}
|