@weglot/translate-react 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +190 -2
- package/build/_virtual/rolldown_runtime.cjs +29 -0
- package/build/_virtual/rolldown_runtime.mjs +7 -0
- package/build/index.cjs +0 -0
- package/build/index.d.cts +2 -0
- package/build/index.d.mts +2 -0
- package/build/index.mjs +1 -0
- package/build/locale.d.cts +6 -0
- package/build/locale.d.cts.map +1 -0
- package/build/locale.d.mts +6 -0
- package/build/locale.d.mts.map +1 -0
- package/build/metadata/manager.cjs +119 -0
- package/build/metadata/manager.mjs +114 -0
- package/build/metadata/manager.mjs.map +1 -0
- package/build/plugin/build-translator.cjs +207 -0
- package/build/plugin/build-translator.mjs +205 -0
- package/build/plugin/build-translator.mjs.map +1 -0
- package/build/plugin/cleanup.cjs +20 -0
- package/build/plugin/cleanup.mjs +20 -0
- package/build/plugin/cleanup.mjs.map +1 -0
- package/build/plugin/index.cjs +0 -0
- package/build/plugin/index.d.cts +2 -0
- package/build/plugin/index.d.mts +2 -0
- package/build/plugin/index.mjs +1 -0
- package/build/plugin/next-compiler-loader.cjs +40 -0
- package/build/plugin/next-compiler-loader.d.cts +12 -0
- package/build/plugin/next-compiler-loader.d.cts.map +1 -0
- package/build/plugin/next-compiler-loader.d.mts +13 -0
- package/build/plugin/next-compiler-loader.d.mts.map +1 -0
- package/build/plugin/next-compiler-loader.mjs +41 -0
- package/build/plugin/next-compiler-loader.mjs.map +1 -0
- package/build/plugin/next-config-loader.cjs +13 -0
- package/build/plugin/next-config-loader.d.cts +8 -0
- package/build/plugin/next-config-loader.d.cts.map +1 -0
- package/build/plugin/next-config-loader.d.mts +9 -0
- package/build/plugin/next-config-loader.d.mts.map +1 -0
- package/build/plugin/next-config-loader.mjs +14 -0
- package/build/plugin/next-config-loader.mjs.map +1 -0
- package/build/plugin/next-locale-client-loader.cjs +9 -0
- package/build/plugin/next-locale-client-loader.d.cts +8 -0
- package/build/plugin/next-locale-client-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-client-loader.d.mts +9 -0
- package/build/plugin/next-locale-client-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-client-loader.mjs +10 -0
- package/build/plugin/next-locale-client-loader.mjs.map +1 -0
- package/build/plugin/next-locale-server-loader.cjs +9 -0
- package/build/plugin/next-locale-server-loader.d.cts +8 -0
- package/build/plugin/next-locale-server-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-server-loader.d.mts +9 -0
- package/build/plugin/next-locale-server-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-server-loader.mjs +10 -0
- package/build/plugin/next-locale-server-loader.mjs.map +1 -0
- package/build/plugin/next.cjs +226 -0
- package/build/plugin/next.d.cts +9 -0
- package/build/plugin/next.d.cts.map +1 -0
- package/build/plugin/next.d.mts +9 -0
- package/build/plugin/next.d.mts.map +1 -0
- package/build/plugin/next.mjs +228 -0
- package/build/plugin/next.mjs.map +1 -0
- package/build/plugin/transform/babel-compat.cjs +13 -0
- package/build/plugin/transform/babel-compat.mjs +10 -0
- package/build/plugin/transform/babel-compat.mjs.map +1 -0
- package/build/plugin/transform/expression-strings.cjs +145 -0
- package/build/plugin/transform/expression-strings.mjs +140 -0
- package/build/plugin/transform/expression-strings.mjs.map +1 -0
- package/build/plugin/transform/index.cjs +45 -0
- package/build/plugin/transform/index.mjs +43 -0
- package/build/plugin/transform/index.mjs.map +1 -0
- package/build/plugin/transform/metadata.cjs +142 -0
- package/build/plugin/transform/metadata.mjs +141 -0
- package/build/plugin/transform/metadata.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +525 -0
- package/build/plugin/transform/process-file.mjs +524 -0
- package/build/plugin/transform/process-file.mjs.map +1 -0
- package/build/plugin/transform/use-i18n.cjs +8 -0
- package/build/plugin/transform/use-i18n.mjs +7 -0
- package/build/plugin/transform/use-i18n.mjs.map +1 -0
- package/build/plugin/transform/utils.cjs +237 -0
- package/build/plugin/transform/utils.mjs +219 -0
- package/build/plugin/transform/utils.mjs.map +1 -0
- package/build/plugin/unplugin.cjs +188 -0
- package/build/plugin/unplugin.d.cts +8 -0
- package/build/plugin/unplugin.d.cts.map +1 -0
- package/build/plugin/unplugin.d.mts +8 -0
- package/build/plugin/unplugin.d.mts.map +1 -0
- package/build/plugin/unplugin.mjs +188 -0
- package/build/plugin/unplugin.mjs.map +1 -0
- package/build/plugin/vite.cjs +27 -0
- package/build/plugin/vite.d.cts +9 -0
- package/build/plugin/vite.d.cts.map +1 -0
- package/build/plugin/vite.d.mts +9 -0
- package/build/plugin/vite.d.mts.map +1 -0
- package/build/plugin/vite.mjs +28 -0
- package/build/plugin/vite.mjs.map +1 -0
- package/build/plugin/webpack.cjs +26 -0
- package/build/plugin/webpack.d.cts +8 -0
- package/build/plugin/webpack.d.cts.map +1 -0
- package/build/plugin/webpack.d.mts +8 -0
- package/build/plugin/webpack.d.mts.map +1 -0
- package/build/plugin/webpack.mjs +27 -0
- package/build/plugin/webpack.mjs.map +1 -0
- package/build/react/client/index.cjs +9 -0
- package/build/react/client/index.d.cts +5 -0
- package/build/react/client/index.d.mts +5 -0
- package/build/react/client/index.mjs +6 -0
- package/build/react/client/useTranslation.cjs +71 -0
- package/build/react/client/useTranslation.d.cts +42 -0
- package/build/react/client/useTranslation.d.cts.map +1 -0
- package/build/react/client/useTranslation.d.mts +42 -0
- package/build/react/client/useTranslation.d.mts.map +1 -0
- package/build/react/client/useTranslation.mjs +71 -0
- package/build/react/client/useTranslation.mjs.map +1 -0
- package/build/react/next/client.cjs +25 -0
- package/build/react/next/client.d.cts +9 -0
- package/build/react/next/client.d.cts.map +1 -0
- package/build/react/next/client.d.mts +9 -0
- package/build/react/next/client.d.mts.map +1 -0
- package/build/react/next/client.mjs +24 -0
- package/build/react/next/client.mjs.map +1 -0
- package/build/react/next/cookie-locale-resolver.cjs +29 -0
- package/build/react/next/cookie-locale-resolver.d.cts +33 -0
- package/build/react/next/cookie-locale-resolver.d.cts.map +1 -0
- package/build/react/next/cookie-locale-resolver.d.mts +33 -0
- package/build/react/next/cookie-locale-resolver.d.mts.map +1 -0
- package/build/react/next/cookie-locale-resolver.mjs +29 -0
- package/build/react/next/cookie-locale-resolver.mjs.map +1 -0
- package/build/react/next/server.cjs +21 -0
- package/build/react/next/server.d.cts +13 -0
- package/build/react/next/server.d.cts.map +1 -0
- package/build/react/next/server.d.mts +14 -0
- package/build/react/next/server.d.mts.map +1 -0
- package/build/react/next/server.mjs +20 -0
- package/build/react/next/server.mjs.map +1 -0
- package/build/react/server/ServerWeglotProvider.cjs +19 -0
- package/build/react/server/ServerWeglotProvider.d.cts +12 -0
- package/build/react/server/ServerWeglotProvider.d.cts.map +1 -0
- package/build/react/server/ServerWeglotProvider.d.mts +12 -0
- package/build/react/server/ServerWeglotProvider.d.mts.map +1 -0
- package/build/react/server/ServerWeglotProvider.mjs +19 -0
- package/build/react/server/ServerWeglotProvider.mjs.map +1 -0
- package/build/react/server/index.cjs +7 -0
- package/build/react/server/index.d.cts +4 -0
- package/build/react/server/index.d.mts +4 -0
- package/build/react/server/index.mjs +5 -0
- package/build/react/server/useTranslation.cjs +60 -0
- package/build/react/server/useTranslation.d.cts +36 -0
- package/build/react/server/useTranslation.d.cts.map +1 -0
- package/build/react/server/useTranslation.d.mts +36 -0
- package/build/react/server/useTranslation.d.mts.map +1 -0
- package/build/react/server/useTranslation.mjs +60 -0
- package/build/react/server/useTranslation.mjs.map +1 -0
- package/build/react/server-only/index.cjs +42 -0
- package/build/react/server-only/index.d.cts +38 -0
- package/build/react/server-only/index.d.cts.map +1 -0
- package/build/react/server-only/index.d.mts +38 -0
- package/build/react/server-only/index.d.mts.map +1 -0
- package/build/react/server-only/index.mjs +42 -0
- package/build/react/server-only/index.mjs.map +1 -0
- package/build/react/server-only/translations.cjs +86 -0
- package/build/react/server-only/translations.mjs +86 -0
- package/build/react/server-only/translations.mjs.map +1 -0
- package/build/react/shared/LocaleSwitcher.cjs +61 -0
- package/build/react/shared/LocaleSwitcher.d.cts +71 -0
- package/build/react/shared/LocaleSwitcher.d.cts.map +1 -0
- package/build/react/shared/LocaleSwitcher.d.mts +71 -0
- package/build/react/shared/LocaleSwitcher.d.mts.map +1 -0
- package/build/react/shared/LocaleSwitcher.mjs +61 -0
- package/build/react/shared/LocaleSwitcher.mjs.map +1 -0
- package/build/react/shared/WeglotContext.cjs +14 -0
- package/build/react/shared/WeglotContext.d.cts +34 -0
- package/build/react/shared/WeglotContext.d.cts.map +1 -0
- package/build/react/shared/WeglotContext.d.mts +34 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -0
- package/build/react/shared/WeglotContext.mjs +13 -0
- package/build/react/shared/WeglotContext.mjs.map +1 -0
- package/build/react/shared/WeglotProvider.cjs +250 -0
- package/build/react/shared/WeglotProvider.d.cts +60 -0
- package/build/react/shared/WeglotProvider.d.cts.map +1 -0
- package/build/react/shared/WeglotProvider.d.mts +60 -0
- package/build/react/shared/WeglotProvider.d.mts.map +1 -0
- package/build/react/shared/WeglotProvider.mjs +250 -0
- package/build/react/shared/WeglotProvider.mjs.map +1 -0
- package/build/react/shared/render-rich-text.cjs +56 -0
- package/build/react/shared/render-rich-text.d.cts +16 -0
- package/build/react/shared/render-rich-text.d.cts.map +1 -0
- package/build/react/shared/render-rich-text.d.mts +16 -0
- package/build/react/shared/render-rich-text.d.mts.map +1 -0
- package/build/react/shared/render-rich-text.mjs +55 -0
- package/build/react/shared/render-rich-text.mjs.map +1 -0
- package/build/react/shared/utils.cjs +34 -0
- package/build/react/shared/utils.mjs +35 -0
- package/build/react/shared/utils.mjs.map +1 -0
- package/build/react/types.d.cts +16 -0
- package/build/react/types.d.cts.map +1 -0
- package/build/react/types.d.mts +16 -0
- package/build/react/types.d.mts.map +1 -0
- package/build/runtime/html/segmenter.cjs +226 -0
- package/build/runtime/html/segmenter.mjs +225 -0
- package/build/runtime/html/segmenter.mjs.map +1 -0
- package/build/runtime/index.cjs +6 -0
- package/build/runtime/index.d.cts +2 -0
- package/build/runtime/index.d.mts +2 -0
- package/build/runtime/index.mjs +3 -0
- package/build/runtime/translate-dynamic.cjs +142 -0
- package/build/runtime/translate-dynamic.d.cts +29 -0
- package/build/runtime/translate-dynamic.d.cts.map +1 -0
- package/build/runtime/translate-dynamic.d.mts +29 -0
- package/build/runtime/translate-dynamic.d.mts.map +1 -0
- package/build/runtime/translate-dynamic.mjs +139 -0
- package/build/runtime/translate-dynamic.mjs.map +1 -0
- package/build/translation-server/logger.cjs +37 -0
- package/build/translation-server/logger.mjs +37 -0
- package/build/translation-server/logger.mjs.map +1 -0
- package/build/translation-server/translation-server.cjs +451 -0
- package/build/translation-server/translation-server.mjs +448 -0
- package/build/translation-server/translation-server.mjs.map +1 -0
- package/build/translators/api.cjs +12 -0
- package/build/translators/api.mjs +12 -0
- package/build/translators/api.mjs.map +1 -0
- package/build/translators/cache-factory.cjs +26 -0
- package/build/translators/cache-factory.mjs +27 -0
- package/build/translators/cache-factory.mjs.map +1 -0
- package/build/translators/local-cache.cjs +132 -0
- package/build/translators/local-cache.mjs +130 -0
- package/build/translators/local-cache.mjs.map +1 -0
- package/build/translators/translation-service.cjs +137 -0
- package/build/translators/translation-service.mjs +138 -0
- package/build/translators/translation-service.mjs.map +1 -0
- package/build/translators/weglot/api-client.cjs +79 -0
- package/build/translators/weglot/api-client.mjs +79 -0
- package/build/translators/weglot/api-client.mjs.map +1 -0
- package/build/translators/weglot/definitions/definitions.generated.cjs +53 -0
- package/build/translators/weglot/definitions/definitions.generated.mjs +52 -0
- package/build/translators/weglot/definitions/definitions.generated.mjs.map +1 -0
- package/build/translators/weglot/engine.cjs +46 -0
- package/build/translators/weglot/engine.mjs +43 -0
- package/build/translators/weglot/engine.mjs.map +1 -0
- package/build/translators/weglot/translator.cjs +61 -0
- package/build/translators/weglot/translator.mjs +62 -0
- package/build/translators/weglot/translator.mjs.map +1 -0
- package/build/translators/weglot/wire-format.cjs +128 -0
- package/build/translators/weglot/wire-format.mjs +129 -0
- package/build/translators/weglot/wire-format.mjs.map +1 -0
- package/build/types.d.cts +143 -0
- package/build/types.d.cts.map +1 -0
- package/build/types.d.mts +143 -0
- package/build/types.d.mts.map +1 -0
- package/build/utils/config-factory.cjs +86 -0
- package/build/utils/config-factory.mjs +83 -0
- package/build/utils/config-factory.mjs.map +1 -0
- package/build/utils/hash.cjs +17 -0
- package/build/utils/hash.mjs +16 -0
- package/build/utils/hash.mjs.map +1 -0
- package/build/utils/is-valid-locale.cjs +13 -0
- package/build/utils/is-valid-locale.mjs +13 -0
- package/build/utils/is-valid-locale.mjs.map +1 -0
- package/build/utils/logger.cjs +51 -0
- package/build/utils/logger.mjs +50 -0
- package/build/utils/logger.mjs.map +1 -0
- package/build/utils/path-helpers.cjs +49 -0
- package/build/utils/path-helpers.mjs +47 -0
- package/build/utils/path-helpers.mjs.map +1 -0
- package/build/utils/timeout.cjs +42 -0
- package/build/utils/timeout.mjs +41 -0
- package/build/utils/timeout.mjs.map +1 -0
- package/build/virtual/code-generator.cjs +56 -0
- package/build/virtual/code-generator.mjs +55 -0
- package/build/virtual/code-generator.mjs.map +1 -0
- package/build/virtual/config.cjs +16 -0
- package/build/virtual/config.d.cts +13 -0
- package/build/virtual/config.d.cts.map +1 -0
- package/build/virtual/config.d.mts +13 -0
- package/build/virtual/config.d.mts.map +1 -0
- package/build/virtual/config.mjs +12 -0
- package/build/virtual/config.mjs.map +1 -0
- package/build/virtual/locale/client.cjs +23 -0
- package/build/virtual/locale/client.d.cts +19 -0
- package/build/virtual/locale/client.d.cts.map +1 -0
- package/build/virtual/locale/client.d.mts +19 -0
- package/build/virtual/locale/client.d.mts.map +1 -0
- package/build/virtual/locale/client.mjs +22 -0
- package/build/virtual/locale/client.mjs.map +1 -0
- package/build/virtual/locale/server.cjs +13 -0
- package/build/virtual/locale/server.d.cts +13 -0
- package/build/virtual/locale/server.d.cts.map +1 -0
- package/build/virtual/locale/server.d.mts +13 -0
- package/build/virtual/locale/server.d.mts.map +1 -0
- package/build/virtual/locale/server.mjs +13 -0
- package/build/virtual/locale/server.mjs.map +1 -0
- package/package.json +260 -4
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { LocaleCode } from "../../locale.cjs";
|
|
2
|
+
import * as react_jsx_runtime1 from "react/jsx-runtime";
|
|
3
|
+
import { PropsWithChildren } from "react";
|
|
4
|
+
|
|
5
|
+
//#region src/react/shared/WeglotProvider.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* Translation provider props
|
|
8
|
+
*/
|
|
9
|
+
type WeglotProviderProps = PropsWithChildren<{
|
|
10
|
+
/**
|
|
11
|
+
* Initial locale to use
|
|
12
|
+
*/
|
|
13
|
+
initialLocale?: LocaleCode;
|
|
14
|
+
/**
|
|
15
|
+
* Initial translations (pre-loaded)
|
|
16
|
+
*/
|
|
17
|
+
initialTranslations?: Record<string, string>;
|
|
18
|
+
/**
|
|
19
|
+
* Optional router instance for Next.js integration
|
|
20
|
+
* If provided, calls router.refresh() after locale change
|
|
21
|
+
* This ensures Server Components re-render with new locale
|
|
22
|
+
*/
|
|
23
|
+
router?: {
|
|
24
|
+
refresh: () => void;
|
|
25
|
+
};
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* Translation Provider Component
|
|
29
|
+
*
|
|
30
|
+
* Wraps your app to provide translation context to all components.
|
|
31
|
+
* Handles locale switching and on-demand translation loading.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```tsx
|
|
35
|
+
* // In your root layout
|
|
36
|
+
* import { WeglotProvider } from '@weglot/translate-react/react';
|
|
37
|
+
*
|
|
38
|
+
* export default function RootLayout({ children }) {
|
|
39
|
+
* return (
|
|
40
|
+
* <html>
|
|
41
|
+
* <body>
|
|
42
|
+
* <WeglotProvider initialLocale="en">
|
|
43
|
+
* {children}
|
|
44
|
+
* </WeglotProvider>
|
|
45
|
+
* </body>
|
|
46
|
+
* </html>
|
|
47
|
+
* );
|
|
48
|
+
* }
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare const WeglotProvider: typeof WeglotProvider__Dev;
|
|
52
|
+
declare function WeglotProvider__Dev({
|
|
53
|
+
initialLocale,
|
|
54
|
+
initialTranslations,
|
|
55
|
+
router,
|
|
56
|
+
children
|
|
57
|
+
}: WeglotProviderProps): react_jsx_runtime1.JSX.Element;
|
|
58
|
+
//#endregion
|
|
59
|
+
export { WeglotProvider, WeglotProviderProps };
|
|
60
|
+
//# sourceMappingURL=WeglotProvider.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WeglotProvider.d.cts","names":[],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":[],"mappings":";;;;;;;;AAwBY,KAAA,mBAAA,GAAsB,iBAAH,CAAA;EAIb;;;EAJiC,aAAA,CAAA,EAIjC,UAJiC;EA+CtC;AAAqE;;EAoIhF,mBAAA,CAAA,EA1KsB,MA0KtB,CAAA,MAAA,EAAA,MAAA,CAAA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cArIW,uBAAc;iBAkIlB,mBAAA;;;;;GAKN,sBAAmB,kBAAA,CAAA,GAAA,CAAA"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { LocaleCode } from "../../locale.mjs";
|
|
2
|
+
import { PropsWithChildren } from "react";
|
|
3
|
+
import * as react_jsx_runtime3 from "react/jsx-runtime";
|
|
4
|
+
|
|
5
|
+
//#region src/react/shared/WeglotProvider.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* Translation provider props
|
|
8
|
+
*/
|
|
9
|
+
type WeglotProviderProps = PropsWithChildren<{
|
|
10
|
+
/**
|
|
11
|
+
* Initial locale to use
|
|
12
|
+
*/
|
|
13
|
+
initialLocale?: LocaleCode;
|
|
14
|
+
/**
|
|
15
|
+
* Initial translations (pre-loaded)
|
|
16
|
+
*/
|
|
17
|
+
initialTranslations?: Record<string, string>;
|
|
18
|
+
/**
|
|
19
|
+
* Optional router instance for Next.js integration
|
|
20
|
+
* If provided, calls router.refresh() after locale change
|
|
21
|
+
* This ensures Server Components re-render with new locale
|
|
22
|
+
*/
|
|
23
|
+
router?: {
|
|
24
|
+
refresh: () => void;
|
|
25
|
+
};
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* Translation Provider Component
|
|
29
|
+
*
|
|
30
|
+
* Wraps your app to provide translation context to all components.
|
|
31
|
+
* Handles locale switching and on-demand translation loading.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```tsx
|
|
35
|
+
* // In your root layout
|
|
36
|
+
* import { WeglotProvider } from '@weglot/translate-react/react';
|
|
37
|
+
*
|
|
38
|
+
* export default function RootLayout({ children }) {
|
|
39
|
+
* return (
|
|
40
|
+
* <html>
|
|
41
|
+
* <body>
|
|
42
|
+
* <WeglotProvider initialLocale="en">
|
|
43
|
+
* {children}
|
|
44
|
+
* </WeglotProvider>
|
|
45
|
+
* </body>
|
|
46
|
+
* </html>
|
|
47
|
+
* );
|
|
48
|
+
* }
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare const WeglotProvider: typeof WeglotProvider__Dev;
|
|
52
|
+
declare function WeglotProvider__Dev({
|
|
53
|
+
initialLocale,
|
|
54
|
+
initialTranslations,
|
|
55
|
+
router,
|
|
56
|
+
children
|
|
57
|
+
}: WeglotProviderProps): react_jsx_runtime3.JSX.Element;
|
|
58
|
+
//#endregion
|
|
59
|
+
export { WeglotProvider, WeglotProviderProps };
|
|
60
|
+
//# sourceMappingURL=WeglotProvider.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WeglotProvider.d.mts","names":[],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":[],"mappings":";;;;;;;;AAwBY,KAAA,mBAAA,GAAsB,iBAAH,CAAA;EAIb;;;EAJiC,aAAA,CAAA,EAIjC,UAJiC;EA+CtC;AAAqE;;EAoIhF,mBAAA,CAAA,EA1KsB,MA0KtB,CAAA,MAAA,EAAA,MAAA,CAAA;EACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cArIW,uBAAc;iBAkIlB,mBAAA;;;;;GAKN,sBAAmB,kBAAA,CAAA,GAAA,CAAA"}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { logger } from "../../utils/logger.mjs";
|
|
4
|
+
import { fetchTranslations } from "./utils.mjs";
|
|
5
|
+
import { WeglotContext } from "./WeglotContext.mjs";
|
|
6
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
7
|
+
import { serverUrl, sourceLocale } from "@weglot/translate-react/virtual/config";
|
|
8
|
+
import { getClientLocale, persistLocale } from "@weglot/translate-react/virtual/locale/client";
|
|
9
|
+
import { jsx } from "react/jsx-runtime";
|
|
10
|
+
|
|
11
|
+
//#region src/react/shared/WeglotProvider.tsx
|
|
12
|
+
const noop = () => {};
|
|
13
|
+
const IS_DEV = process.env.NODE_ENV === "development";
|
|
14
|
+
const BATCH_DELAY = 200;
|
|
15
|
+
/**
|
|
16
|
+
* Translation Provider Component
|
|
17
|
+
*
|
|
18
|
+
* Wraps your app to provide translation context to all components.
|
|
19
|
+
* Handles locale switching and on-demand translation loading.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```tsx
|
|
23
|
+
* // In your root layout
|
|
24
|
+
* import { WeglotProvider } from '@weglot/translate-react/react';
|
|
25
|
+
*
|
|
26
|
+
* export default function RootLayout({ children }) {
|
|
27
|
+
* return (
|
|
28
|
+
* <html>
|
|
29
|
+
* <body>
|
|
30
|
+
* <WeglotProvider initialLocale="en">
|
|
31
|
+
* {children}
|
|
32
|
+
* </WeglotProvider>
|
|
33
|
+
* </body>
|
|
34
|
+
* </html>
|
|
35
|
+
* );
|
|
36
|
+
* }
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
const WeglotProvider = IS_DEV ? WeglotProvider__Dev : WeglotProvider__Prod;
|
|
40
|
+
function WeglotProvider__Prod({ initialLocale, initialTranslations = {}, router, children }) {
|
|
41
|
+
const [locale, setLocaleState] = useState(() => {
|
|
42
|
+
if (initialLocale) return initialLocale;
|
|
43
|
+
if (typeof window !== "undefined") return getClientLocale();
|
|
44
|
+
return sourceLocale;
|
|
45
|
+
});
|
|
46
|
+
const [translations, setTranslations] = useState(initialTranslations);
|
|
47
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
48
|
+
logger.debug(`WeglotProvider initialized with locale: ${locale}`, initialTranslations);
|
|
49
|
+
/**
|
|
50
|
+
* Update HTML lang attribute when locale changes
|
|
51
|
+
* This ensures screen readers and SEO understand the page language
|
|
52
|
+
*/
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
if (typeof document !== "undefined") document.documentElement.lang = locale;
|
|
55
|
+
}, [locale]);
|
|
56
|
+
/**
|
|
57
|
+
* Load translations from public/translations/{locale}.json
|
|
58
|
+
* Lazy loads on-demand for SPAs
|
|
59
|
+
*/
|
|
60
|
+
const loadTranslations = useCallback(async (targetLocale) => {
|
|
61
|
+
if (Object.keys(initialTranslations).length > 0) return;
|
|
62
|
+
setIsLoading(true);
|
|
63
|
+
try {
|
|
64
|
+
const response = await fetch(`/translations/${targetLocale}.json`);
|
|
65
|
+
if (!response.ok) throw new Error(`Failed to load translations for ${targetLocale}: ${response.statusText}`);
|
|
66
|
+
const data = await response.json();
|
|
67
|
+
setTranslations(data.entries || data);
|
|
68
|
+
logger.debug(`Loaded translations for ${targetLocale}:`, Object.keys(data.entries || data).length);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
logger.error(`Failed to load translations for ${targetLocale}:`, error);
|
|
71
|
+
setTranslations({});
|
|
72
|
+
} finally {
|
|
73
|
+
setIsLoading(false);
|
|
74
|
+
}
|
|
75
|
+
}, [initialTranslations]);
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
if (Object.keys(initialTranslations).length === 0) loadTranslations(locale);
|
|
78
|
+
}, []);
|
|
79
|
+
useEffect(() => {
|
|
80
|
+
if (router) setTranslations(initialTranslations);
|
|
81
|
+
}, [initialTranslations, router]);
|
|
82
|
+
/**
|
|
83
|
+
* Change locale
|
|
84
|
+
* - For Next.js SSR: triggers server re-render via router.refresh()
|
|
85
|
+
* - For SPAs: lazy loads translations from /translations/{locale}.json
|
|
86
|
+
*/
|
|
87
|
+
const setLocale = useCallback(async (newLocale) => {
|
|
88
|
+
persistLocale(newLocale);
|
|
89
|
+
setLocaleState(newLocale);
|
|
90
|
+
if (router) router.refresh();
|
|
91
|
+
else await loadTranslations(newLocale);
|
|
92
|
+
}, [router, loadTranslations]);
|
|
93
|
+
return /* @__PURE__ */ jsx(WeglotContext.Provider, {
|
|
94
|
+
value: {
|
|
95
|
+
locale,
|
|
96
|
+
setLocale,
|
|
97
|
+
translations,
|
|
98
|
+
registerHashes: noop,
|
|
99
|
+
isLoading,
|
|
100
|
+
sourceLocale
|
|
101
|
+
},
|
|
102
|
+
children
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
function WeglotProvider__Dev({ initialLocale, initialTranslations = {}, router, children }) {
|
|
106
|
+
const [locale, setLocaleState] = useState(() => {
|
|
107
|
+
if (initialLocale) return initialLocale;
|
|
108
|
+
return getClientLocale();
|
|
109
|
+
});
|
|
110
|
+
const [translations, setTranslations] = useState(initialTranslations);
|
|
111
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
112
|
+
const [allSeenHashes, setAllSeenHashes] = useState(/* @__PURE__ */ new Set());
|
|
113
|
+
const registeredHashesRef = useRef(/* @__PURE__ */ new Set());
|
|
114
|
+
const pendingHashesRef = useRef(/* @__PURE__ */ new Set());
|
|
115
|
+
const erroredHashesRef = useRef(/* @__PURE__ */ new Set());
|
|
116
|
+
const batchTimerRef = useRef(null);
|
|
117
|
+
const translationsRef = useRef(initialTranslations);
|
|
118
|
+
const localeRef = useRef(locale);
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
translationsRef.current = translations;
|
|
121
|
+
}, [translations]);
|
|
122
|
+
useEffect(() => {
|
|
123
|
+
localeRef.current = locale;
|
|
124
|
+
}, [locale]);
|
|
125
|
+
/**
|
|
126
|
+
* Update HTML lang attribute when locale changes
|
|
127
|
+
* This ensures screen readers and SEO understand the page language
|
|
128
|
+
*/
|
|
129
|
+
useEffect(() => {
|
|
130
|
+
if (typeof document !== "undefined") document.documentElement.lang = locale;
|
|
131
|
+
}, [locale]);
|
|
132
|
+
/**
|
|
133
|
+
* Register a hash as being used in a component
|
|
134
|
+
* Called during render - must not trigger state updates immediately
|
|
135
|
+
*/
|
|
136
|
+
const registerHashes = useCallback((hashes) => {
|
|
137
|
+
let wasNew = false;
|
|
138
|
+
hashes.forEach((hash) => {
|
|
139
|
+
wasNew = wasNew || !registeredHashesRef.current.has(hash);
|
|
140
|
+
registeredHashesRef.current.add(hash);
|
|
141
|
+
});
|
|
142
|
+
logger.debug(`Registering hashes: ${hashes.join(", ")}. Registered hashes: ${registeredHashesRef.current.values()}. wasNew: ${wasNew}`);
|
|
143
|
+
if (wasNew) setAllSeenHashes((prev) => {
|
|
144
|
+
const next = prev.union(new Set(hashes));
|
|
145
|
+
logger.debug(`New allSeenHashes: ${[...next.values()]}`);
|
|
146
|
+
return next;
|
|
147
|
+
});
|
|
148
|
+
}, []);
|
|
149
|
+
/**
|
|
150
|
+
* Check for missing translations and request them (batched)
|
|
151
|
+
* This runs when allSeenHashes changes (hot reload or new components mount)
|
|
152
|
+
*/
|
|
153
|
+
useEffect(() => {
|
|
154
|
+
logger.debug(`WeglotProvider checking translations for locale ${locale}, seen hashes: ${allSeenHashes.size}`);
|
|
155
|
+
if (locale === sourceLocale) return;
|
|
156
|
+
const missingHashes = [];
|
|
157
|
+
logger.debug("allSeenHashes: ", [...allSeenHashes.values()], [...pendingHashesRef.current.values()]);
|
|
158
|
+
for (const hash of allSeenHashes) if (!translations[hash] && !pendingHashesRef.current.has(hash) && !erroredHashesRef.current.has(hash)) {
|
|
159
|
+
missingHashes.push(hash);
|
|
160
|
+
pendingHashesRef.current.add(hash);
|
|
161
|
+
}
|
|
162
|
+
logger.debug("Missing hashes: ", missingHashes.join(","));
|
|
163
|
+
if (missingHashes.length === 0 && localeRef.current == locale) return;
|
|
164
|
+
logger.debug(`Requesting translations for ${missingHashes.length} hashes in locale ${locale}`);
|
|
165
|
+
if (batchTimerRef.current) clearTimeout(batchTimerRef.current);
|
|
166
|
+
batchTimerRef.current = setTimeout(async () => {
|
|
167
|
+
const hashesToFetch = Array.from(pendingHashesRef.current);
|
|
168
|
+
pendingHashesRef.current.clear();
|
|
169
|
+
logger.debug(`Fetching translations for ${hashesToFetch.length} hashes`);
|
|
170
|
+
if (hashesToFetch.length === 0) return;
|
|
171
|
+
setIsLoading(true);
|
|
172
|
+
try {
|
|
173
|
+
const newTranslations = await fetchTranslations(localeRef.current, hashesToFetch, serverUrl);
|
|
174
|
+
logger.debug(`Fetched translations for ${hashesToFetch.length} hashes:`, newTranslations);
|
|
175
|
+
const receivedHashes = new Set(Object.keys(newTranslations));
|
|
176
|
+
const missingHashes$1 = hashesToFetch.filter((hash) => !receivedHashes.has(hash));
|
|
177
|
+
if (missingHashes$1.length > 0) {
|
|
178
|
+
logger.warn(`Server did not return translations for ${missingHashes$1.length} hashes: ${missingHashes$1.join(", ")}`);
|
|
179
|
+
for (const hash of missingHashes$1) erroredHashesRef.current.add(hash);
|
|
180
|
+
}
|
|
181
|
+
setTranslations((prev) => ({
|
|
182
|
+
...prev,
|
|
183
|
+
...newTranslations
|
|
184
|
+
}));
|
|
185
|
+
for (const hash of hashesToFetch) registeredHashesRef.current.add(hash);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
logger.warn(`Failed to fetch translations from translation server: ${error}.`);
|
|
188
|
+
for (const hash of hashesToFetch) {
|
|
189
|
+
pendingHashesRef.current.delete(hash);
|
|
190
|
+
erroredHashesRef.current.add(hash);
|
|
191
|
+
}
|
|
192
|
+
} finally {
|
|
193
|
+
setIsLoading(false);
|
|
194
|
+
}
|
|
195
|
+
}, BATCH_DELAY);
|
|
196
|
+
}, [
|
|
197
|
+
allSeenHashes,
|
|
198
|
+
locale,
|
|
199
|
+
translations
|
|
200
|
+
]);
|
|
201
|
+
/**
|
|
202
|
+
* Clear batch timer on unmount
|
|
203
|
+
*/
|
|
204
|
+
useEffect(() => {
|
|
205
|
+
return () => {
|
|
206
|
+
if (batchTimerRef.current) clearTimeout(batchTimerRef.current);
|
|
207
|
+
};
|
|
208
|
+
}, []);
|
|
209
|
+
/**
|
|
210
|
+
* Change locale and load translations dynamically
|
|
211
|
+
*/
|
|
212
|
+
const setLocale = useCallback(async (newLocale) => {
|
|
213
|
+
persistLocale(newLocale);
|
|
214
|
+
setLocaleState(newLocale);
|
|
215
|
+
if (router) router.refresh();
|
|
216
|
+
setIsLoading(true);
|
|
217
|
+
const startTime = performance.now();
|
|
218
|
+
try {
|
|
219
|
+
logger.info(`Fetching translations for locale: ${newLocale}. Server url: ${serverUrl}`);
|
|
220
|
+
const hashes = [...registeredHashesRef.current];
|
|
221
|
+
pendingHashesRef.current.clear();
|
|
222
|
+
erroredHashesRef.current.clear();
|
|
223
|
+
const newTranslations = hashes.length ? await fetchTranslations(newLocale, hashes, serverUrl) : {};
|
|
224
|
+
const endTime = performance.now();
|
|
225
|
+
logger.info(`Translation fetch complete for ${newLocale} in ${(endTime - startTime).toFixed(2)}ms`);
|
|
226
|
+
logger.debug(`Translations loaded for ${newLocale}:`, newTranslations);
|
|
227
|
+
setTranslations(newTranslations);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
logger.error(`Failed to load translations for ${newLocale}:`, error);
|
|
230
|
+
setTranslations({});
|
|
231
|
+
} finally {
|
|
232
|
+
setIsLoading(false);
|
|
233
|
+
}
|
|
234
|
+
}, [router]);
|
|
235
|
+
return /* @__PURE__ */ jsx(WeglotContext.Provider, {
|
|
236
|
+
value: {
|
|
237
|
+
locale,
|
|
238
|
+
setLocale,
|
|
239
|
+
translations,
|
|
240
|
+
registerHashes,
|
|
241
|
+
isLoading,
|
|
242
|
+
sourceLocale
|
|
243
|
+
},
|
|
244
|
+
children
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
//#endregion
|
|
249
|
+
export { WeglotProvider };
|
|
250
|
+
//# sourceMappingURL=WeglotProvider.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WeglotProvider.mjs","names":["missingHashes: string[]","missingHashes"],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type PropsWithChildren,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\nimport { logger } from \"../../utils/logger\";\nimport { fetchTranslations } from \"./utils\";\nimport { serverUrl, sourceLocale } from \"@weglot/translate-react/virtual/config\";\nimport {\n getClientLocale,\n persistLocale,\n} from \"@weglot/translate-react/virtual/locale/client\";\nimport { WeglotContext } from \"./WeglotContext\";\nimport type { LocaleCode } from \"../../locale\";\n\nconst noop = () => {};\n\n/**\n * Translation provider props\n */\nexport type WeglotProviderProps = PropsWithChildren<{\n /**\n * Initial locale to use\n */\n initialLocale?: LocaleCode;\n\n /**\n * Initial translations (pre-loaded)\n */\n initialTranslations?: Record<string, string>;\n\n /**\n * Optional router instance for Next.js integration\n * If provided, calls router.refresh() after locale change\n * This ensures Server Components re-render with new locale\n */\n router?: { refresh: () => void };\n}>;\n\nconst IS_DEV = process.env.NODE_ENV === \"development\";\nconst BATCH_DELAY = 200;\n\n/**\n * Translation Provider Component\n *\n * Wraps your app to provide translation context to all components.\n * Handles locale switching and on-demand translation loading.\n *\n * @example\n * ```tsx\n * // In your root layout\n * import { WeglotProvider } from '@weglot/translate-react/react';\n *\n * export default function RootLayout({ children }) {\n * return (\n * <html>\n * <body>\n * <WeglotProvider initialLocale=\"en\">\n * {children}\n * </WeglotProvider>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\n// Export the appropriate provider directly\nexport const WeglotProvider = IS_DEV ? WeglotProvider__Dev : WeglotProvider__Prod;\n\nfunction WeglotProvider__Prod({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n // Only detect on client-side (not during SSR)\n if (typeof window !== \"undefined\") {\n return getClientLocale();\n }\n return sourceLocale;\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n logger.debug(\n `WeglotProvider initialized with locale: ${locale}`,\n initialTranslations,\n );\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Load translations from public/translations/{locale}.json\n * Lazy loads on-demand for SPAs\n */\n const loadTranslations = useCallback(\n async (targetLocale: LocaleCode) => {\n // If we already have initialTranslations (Next.js SSR), don't fetch\n if (Object.keys(initialTranslations).length > 0) {\n return;\n }\n\n setIsLoading(true);\n try {\n const response = await fetch(`/translations/${targetLocale}.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to load translations for ${targetLocale}: ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n // Translation files have format: { version, locale, entries: {...} }\n setTranslations(data.entries || data);\n logger.debug(\n `Loaded translations for ${targetLocale}:`,\n Object.keys(data.entries || data).length,\n );\n } catch (error) {\n logger.error(`Failed to load translations for ${targetLocale}:`, error);\n // Fallback to empty translations\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [initialTranslations],\n );\n\n // Load translations on mount if not provided via initialTranslations\n useEffect(() => {\n if (Object.keys(initialTranslations).length === 0) {\n loadTranslations(locale);\n }\n }, []); // Only run on mount\n\n useEffect(() => {\n // TODO (AleksandrSl 08/12/2025): More elegant solution required.\n // This is used to update the client part when next app changes locale\n if (router) {\n setTranslations(initialTranslations);\n }\n }, [initialTranslations, router]);\n\n /**\n * Change locale\n * - For Next.js SSR: triggers server re-render via router.refresh()\n * - For SPAs: lazy loads translations from /translations/{locale}.json\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie so server can read it on next render\n persistLocale(newLocale);\n\n // 2. Update local state for immediate UI feedback\n setLocaleState(newLocale);\n\n // 3a. Next.js pattern: Trigger server re-render\n if (router) {\n router.refresh();\n }\n // 3b. SPA pattern: Lazy load translations\n else {\n await loadTranslations(newLocale);\n }\n },\n [router, loadTranslations],\n );\n\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes: noop,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n\nfunction WeglotProvider__Dev({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState(() => {\n if (initialLocale) {\n return initialLocale;\n }\n return getClientLocale();\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n const [allSeenHashes, setAllSeenHashes] = useState<Set<string>>(new Set());\n const registeredHashesRef = useRef<Set<string>>(new Set());\n const pendingHashesRef = useRef<Set<string>>(new Set());\n const erroredHashesRef = useRef<Set<string>>(new Set());\n const batchTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n // Use ref to track translations to avoid stale closures\n const translationsRef = useRef<Record<string, string>>(initialTranslations);\n const localeRef = useRef(locale);\n\n useEffect(() => {\n translationsRef.current = translations;\n }, [translations]);\n\n useEffect(() => {\n localeRef.current = locale;\n }, [locale]);\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Register a hash as being used in a component\n * Called during render - must not trigger state updates immediately\n */\n const registerHashes = useCallback((hashes: string[]) => {\n let wasNew = false;\n hashes.forEach((hash) => {\n wasNew = wasNew || !registeredHashesRef.current.has(hash);\n registeredHashesRef.current.add(hash);\n });\n\n logger.debug(\n `Registering hashes: ${hashes.join(\", \")}. Registered hashes: ${registeredHashesRef.current.values()}. wasNew: ${wasNew}`,\n );\n\n // Schedule a state update for the next tick to track all hashes\n if (wasNew) {\n setAllSeenHashes((prev) => {\n const next = prev.union(new Set(hashes));\n // TODO (AleksandrSl 25/11/2025): Should be a cheaper solution\n logger.debug(`New allSeenHashes: ${[...next.values()]}`);\n return next;\n });\n }\n }, []);\n\n /**\n * Check for missing translations and request them (batched)\n * This runs when allSeenHashes changes (hot reload or new components mount)\n */\n useEffect(() => {\n logger.debug(\n `WeglotProvider checking translations for locale ${locale}, seen hashes: ${allSeenHashes.size}`,\n );\n\n // The source locale has no dictionary; asking would mark every hash failed\n // and stop it being fetched for later locales.\n if (locale === sourceLocale) {\n return;\n }\n\n // Find hashes that are seen but not translated and not already pending\n const missingHashes: string[] = [];\n logger.debug(\n \"allSeenHashes: \",\n [...allSeenHashes.values()],\n [...pendingHashesRef.current.values()],\n );\n for (const hash of allSeenHashes) {\n if (\n !translations[hash] &&\n !pendingHashesRef.current.has(hash) &&\n !erroredHashesRef.current.has(hash)\n ) {\n missingHashes.push(hash);\n pendingHashesRef.current.add(hash);\n }\n }\n logger.debug(\"Missing hashes: \", missingHashes.join(\",\"));\n\n // If no missing hashes, nothing to do\n if (missingHashes.length === 0 && localeRef.current == locale) return;\n\n logger.debug(\n `Requesting translations for ${missingHashes.length} hashes in locale ${locale}`,\n );\n\n // Cancel existing timer\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n\n // Batch the request\n batchTimerRef.current = setTimeout(async () => {\n const hashesToFetch = Array.from(pendingHashesRef.current);\n pendingHashesRef.current.clear();\n\n logger.debug(`Fetching translations for ${hashesToFetch.length} hashes`);\n if (hashesToFetch.length === 0) return;\n\n setIsLoading(true);\n try {\n const newTranslations = await fetchTranslations(\n localeRef.current,\n hashesToFetch,\n serverUrl,\n );\n\n logger.debug(\n `Fetched translations for ${hashesToFetch.length} hashes:`,\n newTranslations,\n );\n\n const receivedHashes = new Set(Object.keys(newTranslations));\n const missingHashes = hashesToFetch.filter(\n (hash) => !receivedHashes.has(hash),\n );\n\n if (missingHashes.length > 0) {\n logger.warn(\n `Server did not return translations for ${missingHashes.length} hashes: ${missingHashes.join(\", \")}`,\n );\n for (const hash of missingHashes) {\n erroredHashesRef.current.add(hash);\n }\n }\n\n setTranslations((prev) => ({ ...prev, ...newTranslations }));\n for (const hash of hashesToFetch) {\n registeredHashesRef.current.add(hash);\n }\n } catch (error) {\n logger.warn(\n `Failed to fetch translations from translation server: ${error}.`,\n );\n // Remove from pending so they can be retried\n for (const hash of hashesToFetch) {\n pendingHashesRef.current.delete(hash);\n erroredHashesRef.current.add(hash);\n }\n } finally {\n setIsLoading(false);\n }\n }, BATCH_DELAY);\n }, [allSeenHashes, locale, translations]);\n\n /**\n * Clear batch timer on unmount\n */\n useEffect(() => {\n return () => {\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n };\n }, []);\n\n /**\n * Change locale and load translations dynamically\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie (unless disabled)\n persistLocale(newLocale);\n\n // 2. Update state\n setLocaleState(newLocale);\n\n // 3. Reload Server Components (if router provided)\n if (router) {\n router.refresh();\n }\n\n setIsLoading(true);\n const startTime = performance.now();\n\n try {\n logger.info(\n `Fetching translations for locale: ${newLocale}. Server url: ${serverUrl}`,\n );\n\n // Everything on the page in one request; later mounts go through batching.\n const hashes = [...registeredHashesRef.current];\n pendingHashesRef.current.clear();\n // A hash that failed for one locale may well exist for the next.\n erroredHashesRef.current.clear();\n\n const newTranslations = hashes.length\n ? await fetchTranslations(newLocale, hashes, serverUrl)\n : {};\n\n const endTime = performance.now();\n logger.info(\n `Translation fetch complete for ${newLocale} in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n logger.debug(`Translations loaded for ${newLocale}:`, newTranslations);\n\n // Replace rather than merge: entries of the previous locale must go.\n setTranslations(newTranslations);\n } catch (error) {\n logger.error(`Failed to load translations for ${newLocale}:`, error);\n // Clear translations on error - components will request individually\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [router],\n );\n\n // TODO (AleksandrSl 24/11/2025): Should I memo the value?\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,aAAa;AAwBnB,MAAM,SAAS,QAAQ,IAAI,aAAa;AACxC,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;AA2BpB,MAAa,iBAAiB,SAAS,sBAAsB;AAE7D,SAAS,qBAAqB,EAC5B,eACA,sBAAsB,EAAE,EACxB,QACA,YACsB;CAEtB,MAAM,CAAC,QAAQ,kBAAkB,eAA2B;AAC1D,MAAI,cAAe,QAAO;AAE1B,MAAI,OAAO,WAAW,YACpB,QAAO,iBAAiB;AAE1B,SAAO;GACP;CACF,MAAM,CAAC,cAAc,mBACnB,SAAiC,oBAAoB;CACvD,MAAM,CAAC,WAAW,gBAAgB,SAAS,MAAM;AAEjD,QAAO,MACL,2CAA2C,UAC3C,oBACD;;;;;AAMD,iBAAgB;AACd,MAAI,OAAO,aAAa,YACtB,UAAS,gBAAgB,OAAO;IAEjC,CAAC,OAAO,CAAC;;;;;CAMZ,MAAM,mBAAmB,YACvB,OAAO,iBAA6B;AAElC,MAAI,OAAO,KAAK,oBAAoB,CAAC,SAAS,EAC5C;AAGF,eAAa,KAAK;AAClB,MAAI;GACF,MAAM,WAAW,MAAM,MAAM,iBAAiB,aAAa,OAAO;AAClE,OAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,mCAAmC,aAAa,IAAI,SAAS,aAC9D;GAGH,MAAM,OAAO,MAAM,SAAS,MAAM;AAElC,mBAAgB,KAAK,WAAW,KAAK;AACrC,UAAO,MACL,2BAA2B,aAAa,IACxC,OAAO,KAAK,KAAK,WAAW,KAAK,CAAC,OACnC;WACM,OAAO;AACd,UAAO,MAAM,mCAAmC,aAAa,IAAI,MAAM;AAEvE,mBAAgB,EAAE,CAAC;YACX;AACR,gBAAa,MAAM;;IAGvB,CAAC,oBAAoB,CACtB;AAGD,iBAAgB;AACd,MAAI,OAAO,KAAK,oBAAoB,CAAC,WAAW,EAC9C,kBAAiB,OAAO;IAEzB,EAAE,CAAC;AAEN,iBAAgB;AAGd,MAAI,OACF,iBAAgB,oBAAoB;IAErC,CAAC,qBAAqB,OAAO,CAAC;;;;;;CAOjC,MAAM,YAAY,YAChB,OAAO,cAA0B;AAE/B,gBAAc,UAAU;AAGxB,iBAAe,UAAU;AAGzB,MAAI,OACF,QAAO,SAAS;MAIhB,OAAM,iBAAiB,UAAU;IAGrC,CAAC,QAAQ,iBAAiB,CAC3B;AAED,QACE,oBAAC,cAAc;EACb,OAAO;GACL;GACA;GACA;GACA,gBAAgB;GAChB;GACA;GACD;EAEA;GACsB;;AAI7B,SAAS,oBAAoB,EAC3B,eACA,sBAAsB,EAAE,EACxB,QACA,YACsB;CAEtB,MAAM,CAAC,QAAQ,kBAAkB,eAAe;AAC9C,MAAI,cACF,QAAO;AAET,SAAO,iBAAiB;GACxB;CACF,MAAM,CAAC,cAAc,mBACnB,SAAiC,oBAAoB;CACvD,MAAM,CAAC,WAAW,gBAAgB,SAAS,MAAM;CAEjD,MAAM,CAAC,eAAe,oBAAoB,yBAAsB,IAAI,KAAK,CAAC;CAC1E,MAAM,sBAAsB,uBAAoB,IAAI,KAAK,CAAC;CAC1D,MAAM,mBAAmB,uBAAoB,IAAI,KAAK,CAAC;CACvD,MAAM,mBAAmB,uBAAoB,IAAI,KAAK,CAAC;CACvD,MAAM,gBAAgB,OAA8B,KAAK;CAGzD,MAAM,kBAAkB,OAA+B,oBAAoB;CAC3E,MAAM,YAAY,OAAO,OAAO;AAEhC,iBAAgB;AACd,kBAAgB,UAAU;IACzB,CAAC,aAAa,CAAC;AAElB,iBAAgB;AACd,YAAU,UAAU;IACnB,CAAC,OAAO,CAAC;;;;;AAMZ,iBAAgB;AACd,MAAI,OAAO,aAAa,YACtB,UAAS,gBAAgB,OAAO;IAEjC,CAAC,OAAO,CAAC;;;;;CAMZ,MAAM,iBAAiB,aAAa,WAAqB;EACvD,IAAI,SAAS;AACb,SAAO,SAAS,SAAS;AACvB,YAAS,UAAU,CAAC,oBAAoB,QAAQ,IAAI,KAAK;AACzD,uBAAoB,QAAQ,IAAI,KAAK;IACrC;AAEF,SAAO,MACL,uBAAuB,OAAO,KAAK,KAAK,CAAC,uBAAuB,oBAAoB,QAAQ,QAAQ,CAAC,YAAY,SAClH;AAGD,MAAI,OACF,mBAAkB,SAAS;GACzB,MAAM,OAAO,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC;AAExC,UAAO,MAAM,sBAAsB,CAAC,GAAG,KAAK,QAAQ,CAAC,GAAG;AACxD,UAAO;IACP;IAEH,EAAE,CAAC;;;;;AAMN,iBAAgB;AACd,SAAO,MACL,mDAAmD,OAAO,iBAAiB,cAAc,OAC1F;AAID,MAAI,WAAW,aACb;EAIF,MAAMA,gBAA0B,EAAE;AAClC,SAAO,MACL,mBACA,CAAC,GAAG,cAAc,QAAQ,CAAC,EAC3B,CAAC,GAAG,iBAAiB,QAAQ,QAAQ,CAAC,CACvC;AACD,OAAK,MAAM,QAAQ,cACjB,KACE,CAAC,aAAa,SACd,CAAC,iBAAiB,QAAQ,IAAI,KAAK,IACnC,CAAC,iBAAiB,QAAQ,IAAI,KAAK,EACnC;AACA,iBAAc,KAAK,KAAK;AACxB,oBAAiB,QAAQ,IAAI,KAAK;;AAGtC,SAAO,MAAM,oBAAoB,cAAc,KAAK,IAAI,CAAC;AAGzD,MAAI,cAAc,WAAW,KAAK,UAAU,WAAW,OAAQ;AAE/D,SAAO,MACL,+BAA+B,cAAc,OAAO,oBAAoB,SACzE;AAGD,MAAI,cAAc,QAChB,cAAa,cAAc,QAAQ;AAIrC,gBAAc,UAAU,WAAW,YAAY;GAC7C,MAAM,gBAAgB,MAAM,KAAK,iBAAiB,QAAQ;AAC1D,oBAAiB,QAAQ,OAAO;AAEhC,UAAO,MAAM,6BAA6B,cAAc,OAAO,SAAS;AACxE,OAAI,cAAc,WAAW,EAAG;AAEhC,gBAAa,KAAK;AAClB,OAAI;IACF,MAAM,kBAAkB,MAAM,kBAC5B,UAAU,SACV,eACA,UACD;AAED,WAAO,MACL,4BAA4B,cAAc,OAAO,WACjD,gBACD;IAED,MAAM,iBAAiB,IAAI,IAAI,OAAO,KAAK,gBAAgB,CAAC;IAC5D,MAAMC,kBAAgB,cAAc,QACjC,SAAS,CAAC,eAAe,IAAI,KAAK,CACpC;AAED,QAAIA,gBAAc,SAAS,GAAG;AAC5B,YAAO,KACL,0CAA0CA,gBAAc,OAAO,WAAWA,gBAAc,KAAK,KAAK,GACnG;AACD,UAAK,MAAM,QAAQA,gBACjB,kBAAiB,QAAQ,IAAI,KAAK;;AAItC,qBAAiB,UAAU;KAAE,GAAG;KAAM,GAAG;KAAiB,EAAE;AAC5D,SAAK,MAAM,QAAQ,cACjB,qBAAoB,QAAQ,IAAI,KAAK;YAEhC,OAAO;AACd,WAAO,KACL,yDAAyD,MAAM,GAChE;AAED,SAAK,MAAM,QAAQ,eAAe;AAChC,sBAAiB,QAAQ,OAAO,KAAK;AACrC,sBAAiB,QAAQ,IAAI,KAAK;;aAE5B;AACR,iBAAa,MAAM;;KAEpB,YAAY;IACd;EAAC;EAAe;EAAQ;EAAa,CAAC;;;;AAKzC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,QAChB,cAAa,cAAc,QAAQ;;IAGtC,EAAE,CAAC;;;;CAKN,MAAM,YAAY,YAChB,OAAO,cAA0B;AAE/B,gBAAc,UAAU;AAGxB,iBAAe,UAAU;AAGzB,MAAI,OACF,QAAO,SAAS;AAGlB,eAAa,KAAK;EAClB,MAAM,YAAY,YAAY,KAAK;AAEnC,MAAI;AACF,UAAO,KACL,qCAAqC,UAAU,gBAAgB,YAChE;GAGD,MAAM,SAAS,CAAC,GAAG,oBAAoB,QAAQ;AAC/C,oBAAiB,QAAQ,OAAO;AAEhC,oBAAiB,QAAQ,OAAO;GAEhC,MAAM,kBAAkB,OAAO,SAC3B,MAAM,kBAAkB,WAAW,QAAQ,UAAU,GACrD,EAAE;GAEN,MAAM,UAAU,YAAY,KAAK;AACjC,UAAO,KACL,kCAAkC,UAAU,OAAO,UAAU,WAAW,QAAQ,EAAE,CAAC,IACpF;AAED,UAAO,MAAM,2BAA2B,UAAU,IAAI,gBAAgB;AAGtE,mBAAgB,gBAAgB;WACzB,OAAO;AACd,UAAO,MAAM,mCAAmC,UAAU,IAAI,MAAM;AAEpE,mBAAgB,EAAE,CAAC;YACX;AACR,gBAAa,MAAM;;IAGvB,CAAC,OAAO,CACT;AAGD,QACE,oBAAC,cAAc;EACb,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACD;EAEA;GACsB"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_logger = require('../../utils/logger.cjs');
|
|
3
|
+
let react = require("react");
|
|
4
|
+
let react_jsx_runtime = require("react/jsx-runtime");
|
|
5
|
+
let intl_messageformat = require("intl-messageformat");
|
|
6
|
+
intl_messageformat = require_rolldown_runtime.__toESM(intl_messageformat);
|
|
7
|
+
|
|
8
|
+
//#region src/react/shared/render-rich-text.tsx
|
|
9
|
+
/**
|
|
10
|
+
* Wraps a FormatXMLElementFn to key its parts: they become the returned
|
|
11
|
+
* element's children, and an unkeyed one among them makes React warn.
|
|
12
|
+
*/
|
|
13
|
+
function assignUniqueKeysToParts(formatXMLElementFn) {
|
|
14
|
+
return function(parts) {
|
|
15
|
+
return formatXMLElementFn(parts.map((part, index) => (0, react.isValidElement)(part) ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: part }, index) : part));
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Wraps all FormatXMLElementFn values in params with key assignment
|
|
20
|
+
*/
|
|
21
|
+
function assignUniqueKeysToParams(params) {
|
|
22
|
+
const result = {};
|
|
23
|
+
for (const [key, value] of Object.entries(params)) if (typeof value === "function") result[key] = assignUniqueKeysToParts(value);
|
|
24
|
+
else result[key] = value;
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Parse rich text translation string with placeholders (server-side version)
|
|
29
|
+
*
|
|
30
|
+
* Supports:
|
|
31
|
+
* - ICU MessageFormat: {count, plural, one {# item} other {# items}}
|
|
32
|
+
* - Variable placeholders: {name}
|
|
33
|
+
* - Component placeholders: <tag0>content</tag0>
|
|
34
|
+
*
|
|
35
|
+
* @param text - The translation string with placeholders
|
|
36
|
+
* @param params - Object with variable values and component renderers
|
|
37
|
+
* @param locale
|
|
38
|
+
* @returns React nodes or string
|
|
39
|
+
*/
|
|
40
|
+
function renderRichText(text, params, locale) {
|
|
41
|
+
try {
|
|
42
|
+
const formatter = new intl_messageformat.default(text, locale);
|
|
43
|
+
const keyedParams = assignUniqueKeysToParams(params);
|
|
44
|
+
const result = formatter.format(keyedParams);
|
|
45
|
+
if (Array.isArray(result)) return result.map((item, index) => {
|
|
46
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: item }, index);
|
|
47
|
+
});
|
|
48
|
+
return result;
|
|
49
|
+
} catch (error) {
|
|
50
|
+
require_logger.logger.warn(`Error rendering rich text (${text}): ${error}`);
|
|
51
|
+
return text;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
//#endregion
|
|
56
|
+
exports.renderRichText = renderRichText;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ReactNode } from "react";
|
|
2
|
+
import { FormatXMLElementFn } from "intl-messageformat";
|
|
3
|
+
|
|
4
|
+
//#region src/react/shared/render-rich-text.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Component renderer function for rich text translation
|
|
8
|
+
*/
|
|
9
|
+
type ComponentRenderer = FormatXMLElementFn<ReactNode>;
|
|
10
|
+
/**
|
|
11
|
+
* Rich text parameters for translation
|
|
12
|
+
*/
|
|
13
|
+
type RichTextParams = Record<string, ReactNode | ComponentRenderer>;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { RichTextParams };
|
|
16
|
+
//# sourceMappingURL=render-rich-text.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-rich-text.d.cts","names":[],"sources":["../../../src/react/shared/render-rich-text.tsx"],"sourcesContent":[],"mappings":";;;;;;AAQA;AAKA;AAA4C,KALhC,iBAAA,GAAoB,kBAKY,CALO,SAKP,CAAA;;;;KAAhC,cAAA,GAAiB,eAAe,YAAY"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ReactNode } from "react";
|
|
2
|
+
import { FormatXMLElementFn } from "intl-messageformat";
|
|
3
|
+
|
|
4
|
+
//#region src/react/shared/render-rich-text.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Component renderer function for rich text translation
|
|
8
|
+
*/
|
|
9
|
+
type ComponentRenderer = FormatXMLElementFn<ReactNode>;
|
|
10
|
+
/**
|
|
11
|
+
* Rich text parameters for translation
|
|
12
|
+
*/
|
|
13
|
+
type RichTextParams = Record<string, ReactNode | ComponentRenderer>;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { RichTextParams };
|
|
16
|
+
//# sourceMappingURL=render-rich-text.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-rich-text.d.mts","names":[],"sources":["../../../src/react/shared/render-rich-text.tsx"],"sourcesContent":[],"mappings":";;;;;;AAQA;AAKA;AAA4C,KALhC,iBAAA,GAAoB,kBAKY,CALO,SAKP,CAAA;;;;KAAhC,cAAA,GAAiB,eAAe,YAAY"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { logger } from "../../utils/logger.mjs";
|
|
2
|
+
import { Fragment, isValidElement } from "react";
|
|
3
|
+
import { jsx } from "react/jsx-runtime";
|
|
4
|
+
import IntlMessageFormat from "intl-messageformat";
|
|
5
|
+
|
|
6
|
+
//#region src/react/shared/render-rich-text.tsx
|
|
7
|
+
/**
|
|
8
|
+
* Wraps a FormatXMLElementFn to key its parts: they become the returned
|
|
9
|
+
* element's children, and an unkeyed one among them makes React warn.
|
|
10
|
+
*/
|
|
11
|
+
function assignUniqueKeysToParts(formatXMLElementFn) {
|
|
12
|
+
return function(parts) {
|
|
13
|
+
return formatXMLElementFn(parts.map((part, index) => isValidElement(part) ? /* @__PURE__ */ jsx(Fragment, { children: part }, index) : part));
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Wraps all FormatXMLElementFn values in params with key assignment
|
|
18
|
+
*/
|
|
19
|
+
function assignUniqueKeysToParams(params) {
|
|
20
|
+
const result = {};
|
|
21
|
+
for (const [key, value] of Object.entries(params)) if (typeof value === "function") result[key] = assignUniqueKeysToParts(value);
|
|
22
|
+
else result[key] = value;
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Parse rich text translation string with placeholders (server-side version)
|
|
27
|
+
*
|
|
28
|
+
* Supports:
|
|
29
|
+
* - ICU MessageFormat: {count, plural, one {# item} other {# items}}
|
|
30
|
+
* - Variable placeholders: {name}
|
|
31
|
+
* - Component placeholders: <tag0>content</tag0>
|
|
32
|
+
*
|
|
33
|
+
* @param text - The translation string with placeholders
|
|
34
|
+
* @param params - Object with variable values and component renderers
|
|
35
|
+
* @param locale
|
|
36
|
+
* @returns React nodes or string
|
|
37
|
+
*/
|
|
38
|
+
function renderRichText(text, params, locale) {
|
|
39
|
+
try {
|
|
40
|
+
const formatter = new IntlMessageFormat(text, locale);
|
|
41
|
+
const keyedParams = assignUniqueKeysToParams(params);
|
|
42
|
+
const result = formatter.format(keyedParams);
|
|
43
|
+
if (Array.isArray(result)) return result.map((item, index) => {
|
|
44
|
+
return /* @__PURE__ */ jsx(Fragment, { children: item }, index);
|
|
45
|
+
});
|
|
46
|
+
return result;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
logger.warn(`Error rendering rich text (${text}): ${error}`);
|
|
49
|
+
return text;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
//#endregion
|
|
54
|
+
export { renderRichText };
|
|
55
|
+
//# sourceMappingURL=render-rich-text.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-rich-text.mjs","names":["result: RichTextParams"],"sources":["../../../src/react/shared/render-rich-text.tsx"],"sourcesContent":["import { Fragment, isValidElement, type ReactNode } from \"react\";\nimport IntlMessageFormat, { type FormatXMLElementFn } from \"intl-messageformat\";\nimport { logger } from \"../../utils/logger\";\nimport type { LocaleCode } from \"../../locale\";\n\n/**\n * Component renderer function for rich text translation\n */\nexport type ComponentRenderer = FormatXMLElementFn<ReactNode>;\n\n/**\n * Rich text parameters for translation\n */\nexport type RichTextParams = Record<string, ReactNode | ComponentRenderer>;\n\n/**\n * Wraps a FormatXMLElementFn to key its parts: they become the returned\n * element's children, and an unkeyed one among them makes React warn.\n */\nfunction assignUniqueKeysToParts(\n formatXMLElementFn: FormatXMLElementFn<ReactNode>,\n): FormatXMLElementFn<ReactNode> {\n return function (parts: Array<ReactNode>) {\n return formatXMLElementFn(\n parts.map((part, index) =>\n isValidElement(part) ? <Fragment key={index}>{part}</Fragment> : part,\n ),\n );\n };\n}\n\n/**\n * Wraps all FormatXMLElementFn values in params with key assignment\n */\nfunction assignUniqueKeysToParams(params: RichTextParams): RichTextParams {\n const result: RichTextParams = {};\n\n for (const [key, value] of Object.entries(params)) {\n // Check if value is a FormatXMLElementFn (function that's not a React component)\n if (typeof value === \"function\") {\n result[key] = assignUniqueKeysToParts(value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n//\n\n/**\n * Parse rich text translation string with placeholders (server-side version)\n *\n * Supports:\n * - ICU MessageFormat: {count, plural, one {# item} other {# items}}\n * - Variable placeholders: {name}\n * - Component placeholders: <tag0>content</tag0>\n *\n * @param text - The translation string with placeholders\n * @param params - Object with variable values and component renderers\n * @param locale\n * @returns React nodes or string\n */\nexport function renderRichText(\n text: string,\n params: RichTextParams,\n locale: LocaleCode,\n): ReactNode {\n try {\n const formatter = new IntlMessageFormat(text, locale);\n const keyedParams = assignUniqueKeysToParams(params);\n const result = formatter.format<ReactNode>(keyedParams);\n\n if (Array.isArray(result)) {\n // Making all elements keyed here somehow fixes all the things. Maybe I also need to key everything in toKeyedReactNodeArray and I just don't get the error because I don't have a corner case for it? Need to investigate\n return result.map((item, index) => {\n // Each item gets wrapped in Fragment with unique key\n // This handles strings, React elements (like <>text</>), everything\n return <Fragment key={index}>{item}</Fragment>;\n });\n }\n\n return result;\n } catch (error) {\n // It's better to render at least something than break the whole app.\n logger.warn(`Error rendering rich text (${text}): ${error}`);\n return text;\n }\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAS,wBACP,oBAC+B;AAC/B,QAAO,SAAU,OAAyB;AACxC,SAAO,mBACL,MAAM,KAAK,MAAM,UACf,eAAe,KAAK,GAAG,oBAAC,sBAAsB,QAAR,MAAwB,GAAG,KAClE,CACF;;;;;;AAOL,SAAS,yBAAyB,QAAwC;CACxE,MAAMA,SAAyB,EAAE;AAEjC,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,CAE/C,KAAI,OAAO,UAAU,WACnB,QAAO,OAAO,wBAAwB,MAAM;KAE5C,QAAO,OAAO;AAIlB,QAAO;;;;;;;;;;;;;;;AAiBT,SAAgB,eACd,MACA,QACA,QACW;AACX,KAAI;EACF,MAAM,YAAY,IAAI,kBAAkB,MAAM,OAAO;EACrD,MAAM,cAAc,yBAAyB,OAAO;EACpD,MAAM,SAAS,UAAU,OAAkB,YAAY;AAEvD,MAAI,MAAM,QAAQ,OAAO,CAEvB,QAAO,OAAO,KAAK,MAAM,UAAU;AAGjC,UAAO,oBAAC,sBAAsB,QAAR,MAAwB;IAC9C;AAGJ,SAAO;UACA,OAAO;AAEd,SAAO,KAAK,8BAA8B,KAAK,KAAK,QAAQ;AAC5D,SAAO"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const require_logger = require('../../utils/logger.cjs');
|
|
2
|
+
|
|
3
|
+
//#region src/react/shared/utils.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fetch translations from translation server
|
|
6
|
+
* Times out after 30 seconds to prevent indefinite hangs
|
|
7
|
+
*/
|
|
8
|
+
async function fetchTranslations(targetLocale, hashes, serverUrl) {
|
|
9
|
+
if (!serverUrl) return {};
|
|
10
|
+
if (!hashes || hashes.length === 0) return {};
|
|
11
|
+
const url = `${serverUrl}/translations/${targetLocale}`;
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
const timeoutId = setTimeout(() => controller.abort(), 3e4);
|
|
14
|
+
try {
|
|
15
|
+
let response = await fetch(url, {
|
|
16
|
+
method: "POST",
|
|
17
|
+
headers: { "Content-Type": "application/json" },
|
|
18
|
+
body: JSON.stringify({ hashes }),
|
|
19
|
+
signal: controller.signal
|
|
20
|
+
});
|
|
21
|
+
if (!response.ok) throw new Error(`Translation API error: ${response.statusText}`);
|
|
22
|
+
const result = await response.json();
|
|
23
|
+
require_logger.logger.debug(`Fetched translations for ${targetLocale}: ${JSON.stringify(result)}`);
|
|
24
|
+
return result.translations || {};
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (error instanceof Error && error.name === "AbortError") throw new Error(`Translation request to ${targetLocale} timed out after 30 seconds`);
|
|
27
|
+
throw error;
|
|
28
|
+
} finally {
|
|
29
|
+
clearTimeout(timeoutId);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//#endregion
|
|
34
|
+
exports.fetchTranslations = fetchTranslations;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { logger } from "../../utils/logger.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/react/shared/utils.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fetch translations from translation server
|
|
6
|
+
* Times out after 30 seconds to prevent indefinite hangs
|
|
7
|
+
*/
|
|
8
|
+
async function fetchTranslations(targetLocale, hashes, serverUrl) {
|
|
9
|
+
if (!serverUrl) return {};
|
|
10
|
+
if (!hashes || hashes.length === 0) return {};
|
|
11
|
+
const url = `${serverUrl}/translations/${targetLocale}`;
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
const timeoutId = setTimeout(() => controller.abort(), 3e4);
|
|
14
|
+
try {
|
|
15
|
+
let response = await fetch(url, {
|
|
16
|
+
method: "POST",
|
|
17
|
+
headers: { "Content-Type": "application/json" },
|
|
18
|
+
body: JSON.stringify({ hashes }),
|
|
19
|
+
signal: controller.signal
|
|
20
|
+
});
|
|
21
|
+
if (!response.ok) throw new Error(`Translation API error: ${response.statusText}`);
|
|
22
|
+
const result = await response.json();
|
|
23
|
+
logger.debug(`Fetched translations for ${targetLocale}: ${JSON.stringify(result)}`);
|
|
24
|
+
return result.translations || {};
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (error instanceof Error && error.name === "AbortError") throw new Error(`Translation request to ${targetLocale} timed out after 30 seconds`);
|
|
27
|
+
throw error;
|
|
28
|
+
} finally {
|
|
29
|
+
clearTimeout(timeoutId);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//#endregion
|
|
34
|
+
export { fetchTranslations };
|
|
35
|
+
//# sourceMappingURL=utils.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":[],"sources":["../../../src/react/shared/utils.ts"],"sourcesContent":["import { logger } from \"../../utils/logger\";\n\n/**\n * Fetch translations from translation server\n * Times out after 30 seconds to prevent indefinite hangs\n */\nexport async function fetchTranslations(\n targetLocale: string,\n hashes: string[],\n serverUrl?: string,\n): Promise<Record<string, string>> {\n if (!serverUrl) {\n return {};\n }\n if (!hashes || hashes.length === 0) {\n // This function is only called in dev mode and there is no need to fetch all the translations at once in dev mode\n return {};\n }\n const url = `${serverUrl}/translations/${targetLocale}`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout\n\n try {\n let response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ hashes }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Translation API error: ${response.statusText}`);\n }\n\n // TODO (AleksandrSl 02/12/2025): Handle errors in the context.\n const result = await response.json();\n\n logger.debug(\n `Fetched translations for ${targetLocale}: ${JSON.stringify(result)}`,\n );\n\n // Server returns { locale, translations, errors }\n // Extract just the translations dictionary\n return result.translations || {};\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(\n `Translation request to ${targetLocale} timed out after 30 seconds`,\n );\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n"],"mappings":";;;;;;;AAMA,eAAsB,kBACpB,cACA,QACA,WACiC;AACjC,KAAI,CAAC,UACH,QAAO,EAAE;AAEX,KAAI,CAAC,UAAU,OAAO,WAAW,EAE/B,QAAO,EAAE;CAEX,MAAM,MAAM,GAAG,UAAU,gBAAgB;CAEzC,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,YAAY,iBAAiB,WAAW,OAAO,EAAE,IAAM;AAE7D,KAAI;EACF,IAAI,WAAW,MAAM,MAAM,KAAK;GAC9B,QAAQ;GACR,SAAS,EACP,gBAAgB,oBACjB;GACD,MAAM,KAAK,UAAU,EAAE,QAAQ,CAAC;GAChC,QAAQ,WAAW;GACpB,CAAC;AAEF,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MAAM,0BAA0B,SAAS,aAAa;EAIlE,MAAM,SAAS,MAAM,SAAS,MAAM;AAEpC,SAAO,MACL,4BAA4B,aAAa,IAAI,KAAK,UAAU,OAAO,GACpE;AAID,SAAO,OAAO,gBAAgB,EAAE;UACzB,OAAO;AACd,MAAI,iBAAiB,SAAS,MAAM,SAAS,aAC3C,OAAM,IAAI,MACR,0BAA0B,aAAa,6BACxC;AAEH,QAAM;WACE;AACR,eAAa,UAAU"}
|