Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | 332x 332x 644x 10x 332x 132x 332x 654x 733x 733x 132x 132x 332x 654x 654x 654x 332x 6423x 93795x 93795x 93795x 641x 281x 93795x 6423x 3733x 109x 3624x 3624x 6423x 59x 6423x 110x 110x 110x 332x 332x 6103x 6103x 6103x 1940x 1816x 66x 66x 66x 66x 6103x 987x 6429x 6423x 652x 6423x 1658x 1940x 1940x 2652x | import type { PropsWithChildren } from "react";
import { isServer } from "@tanstack/react-query";
import { createInstance } from "i18next";
import type {
i18n as I18n,
InitOptions,
PostProcessorModule,
Resource,
} from "i18next";
import { I18nextProvider } from "react-i18next";
import { capitalize, clone, keys, unique } from "remeda";
import { z } from "zod";
import type { TRPCError } from "~app/trpc";
import { promisifyEvent } from "~utils/promise";
import type { Language, Namespace } from "./i18n-data";
import { baseLanguage, defaultNamespace, languages } from "./i18n-data";
const i18nInitOptions: InitOptions = {
fallbackLng: baseLanguage,
defaultNS: defaultNamespace,
ns: [defaultNamespace],
supportedLngs: keys(languages),
interpolation: {
// React doesn't need to escape values
escapeValue: false,
},
postProcess: "capitalize",
partialBundledLanguages: true,
};
export const validatorLocales: Record<
Language,
// oxlint-disable-next-line typescript/consistent-type-imports
() => Promise<typeof import("zod/v4/locales/en.js")>
> = {
en: () => import("zod/v4/locales/en.js"),
ru: () => import("zod/v4/locales/ru.js"),
};
const translateValidatorMessage = ({
instance,
key,
params: { target, ...rest },
language,
}: {
instance: I18n;
key: string;
params: Record<string, unknown>;
language: Language;
}) =>
instance.t(key, {
...rest,
target:
typeof target === "string"
? instance.t(target, { lng: language, defaultValue: target })
: target,
lng: language,
defaultValue: key,
});
export const getValidatorMessageFactory =
(instance: I18n, language: Language) =>
(issue: { code: string; params?: Record<string, unknown> }) => {
const { i18nKey, ...params } = issue.params ?? {};
Iif (typeof i18nKey !== "string") {
return;
}
Eif (instance.exists(i18nKey, { lng: language })) {
return capitalize(
translateValidatorMessage({ instance, key: i18nKey, params, language }),
);
}
if (instance.exists(i18nKey, { lng: baseLanguage })) {
return translateValidatorMessage({
instance,
key: i18nKey,
params,
language: baseLanguage,
});
}
};
export const changeValidatorLocale = async (
language: Language,
instance: I18n,
) => {
Iif (isServer) {
throw new Error(`Expected to call "changeValidatorLocale" only on client`);
}
const { default: locale } = await validatorLocales[language]();
z.config({
...locale(),
customError: getValidatorMessageFactory(instance, language),
});
};
const addFormatters = (instance: I18n) => {
instance.use({
type: "postProcessor",
name: "capitalize",
process: (value, key) => {
const arrayKey = Array.isArray(key) ? key : [key];
const firstKey = arrayKey[0] || "";
if (
firstKey.startsWith("toasts") &&
["success", "error", "mutate"].some((suffix) =>
firstKey.endsWith(suffix),
)
) {
// We should always capitalize toast messages
return capitalize(value);
}
return value;
},
} satisfies PostProcessorModule);
/* oxlint-disable typescript/no-non-null-assertion */
instance.services.formatter!.add("and", (messages: string[]) => {
if (messages.length === 1) {
return messages.join("");
}
const t = instance.getFixedT(instance.language);
return [messages.slice(0, -1).join(", "), ...messages.slice(-1)].join(
t("common.andJoiner"),
);
});
instance.services.formatter!.add("uniqueErrors", (errors: TRPCError[]) =>
unique(errors.map((error) => error.message)).join("\n"),
);
instance.services.formatter!.add(
// Inline plural format
// Translation: `{ "foo": "Creating {{countVar, plural(one:item;other:{count} items)}}" }`
// Resolves `t("foo", {countVar: 3})` to `Creating 3 items`
"plural",
(
value: number,
lng: string | undefined,
options: Record<Intl.LDMLPluralRule, string>,
) => {
const pluralRules = new Intl.PluralRules(lng || baseLanguage);
const result = pluralRules.select(value);
return (options[result] || options.other).replace(
"{count}",
value.toString(),
);
},
);
/* oxlint-enable typescript/no-non-null-assertion */
};
const id = <T,>(a: T): T => a;
/*
i18n flow
Server:
- instance is created on server (with fixed lng & loaded resources)
- server provides instance via `Provider`
Client:
- instance lng & resources are dehydrated to client via `serializeContext`
- client hydrates them via `onHydrate`
- client provides hydrated instance via `Provider`
*/
export const createI18nContext = ({
getLanguage,
beforeInit = id,
isInitializable,
}: {
getLanguage: () => Language;
beforeInit?: (instance: I18n) => I18n;
isInitializable?: boolean;
}) => {
const initialLanguage = getLanguage();
const instance = beforeInit(
// Options are cloned because i18next mutates properties inline
// causing different request to get same e.g. namespaces
createInstance(clone(i18nInitOptions)),
);
const ensureInitialized = () => {
if (instance.isInitialized) {
return;
}
Eif (instance.isInitializing) {
return promisifyEvent((listener) => {
instance.on("initialized", listener);
return () => instance.off("initialized", listener);
});
}
if (isInitializable) {
return instance.init({ lng: initialLanguage }, () =>
addFormatters(instance),
);
}
// This is a log we should see on client in case instance was not initialized
// oxlint-disable-next-line no-console
console.error(
`Expected to be in either pending or resolved initialized state`,
);
};
return {
instance,
serializeContext: () => ({
language: instance.language as Language,
data: instance.store.data,
}),
initialize: async (
serializedData: Partial<{ language: Language; data: Resource }>,
) => {
await instance.init({
lng: serializedData.language,
resources: serializedData.data,
});
if (!isServer) {
await changeValidatorLocale(
serializedData.language ?? initialLanguage,
instance,
);
}
addFormatters(instance);
},
Provider: ({ children }: PropsWithChildren) => (
<I18nextProvider i18n={instance}>{children}</I18nextProvider>
),
loadNamespaces: async (...namespaces: Namespace[]) => {
await ensureInitialized();
return instance.loadNamespaces(["default", ...namespaces]);
},
getTranslation: () => instance.getFixedT(initialLanguage),
getNamespacedTranslation: <N extends Namespace>(namespace: N) =>
instance.getFixedT(initialLanguage, namespace),
};
};
export type I18nContext = ReturnType<typeof createI18nContext>;
|