@tolgee/react 5.29.5 → 5.29.6-prerelease.fc7efe8f.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.
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { TolgeeInstance } from '@tolgee/web';
2
+ import { TolgeeInstance, TolgeeStaticData } from '@tolgee/web';
3
3
  import { ReactOptions, TolgeeReactContext } from './types';
4
4
  export declare const DEFAULT_REACT_OPTIONS: ReactOptions;
5
5
  export declare const getProviderInstance: () => React.Context<TolgeeReactContext | undefined>;
@@ -8,5 +8,13 @@ export interface TolgeeProviderProps {
8
8
  tolgee: TolgeeInstance;
9
9
  options?: ReactOptions;
10
10
  fallback?: React.ReactNode;
11
+ /**
12
+ * Hard set language to this value, use together with `staticData`
13
+ */
14
+ language?: string;
15
+ /**
16
+ * If provided, static data will be hard set to Tolgee cache for initial render
17
+ */
18
+ staticData?: TolgeeStaticData;
11
19
  }
12
20
  export declare const TolgeeProvider: React.FC<TolgeeProviderProps>;
@@ -9,6 +9,62 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
9
9
 
10
10
  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
11
11
 
12
+ function getTolgeeWithDeactivatedWrapper(tolgee) {
13
+ return Object.assign(Object.assign({}, tolgee), { t(...args) {
14
+ // @ts-ignore
15
+ const props = web.getTranslateProps(...args);
16
+ return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
17
+ } });
18
+ }
19
+ /**
20
+ * Updates tolgee static data and language, to be ready right away for the first render
21
+ * and therefore compatible with SSR.
22
+ *
23
+ * It also ensures that the first render is done without wrapping and so it avoids
24
+ * "client different than server" issues.
25
+ *
26
+ * If no language data and static data are provided no action is taken
27
+ *
28
+ * @param tolgeeInstance initialized Tolgee instance
29
+ * @param language language that is obtained outside of Tolgee on the server and client
30
+ * @param staticData static data for the language
31
+ */
32
+ function useTolgeeSSR(tolgeeInstance, language, staticData) {
33
+ const enabled = Boolean(language || staticData);
34
+ const [noWrappingTolgee] = React.useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
35
+ const [initialRender, setInitialRender] = React.useState(enabled);
36
+ React.useEffect(() => {
37
+ setInitialRender(false);
38
+ }, []);
39
+ React.useMemo(() => {
40
+ // we have to prepare tolgee before rendering children
41
+ // so translations are available right away
42
+ // events emitting must be off, to not trigger re-render while rendering
43
+ if (enabled) {
44
+ tolgeeInstance.setEmitterActive(false);
45
+ tolgeeInstance.addStaticData(staticData);
46
+ tolgeeInstance.changeLanguage(language);
47
+ tolgeeInstance.setEmitterActive(true);
48
+ }
49
+ }, [language, staticData, tolgeeInstance]);
50
+ React.useState(() => {
51
+ if (enabled && web.isSSR()) {
52
+ // running this function only on first render
53
+ if (!tolgeeInstance.isLoaded()) {
54
+ // warning user, that static data provided are not sufficient
55
+ // for proper SSR render
56
+ const missingRecords = tolgeeInstance
57
+ .getRequiredRecords(language)
58
+ .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
59
+ .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
60
+ // eslint-disable-next-line no-console
61
+ console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
62
+ }
63
+ }
64
+ });
65
+ return initialRender ? noWrappingTolgee : tolgeeInstance;
66
+ }
67
+
12
68
  const DEFAULT_REACT_OPTIONS = {
13
69
  useSuspense: true,
14
70
  };
@@ -20,8 +76,7 @@ const getProviderInstance = () => {
20
76
  return ProviderInstance;
21
77
  };
22
78
  let LAST_TOLGEE_INSTANCE = undefined;
23
- const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
24
- const [loading, setLoading] = React.useState(!tolgee.isLoaded());
79
+ const TolgeeProvider = ({ tolgee, options, children, fallback, staticData, language, }) => {
25
80
  // prevent restarting tolgee unnecesarly
26
81
  // however if the instance change on hot-reloading
27
82
  // we want to restart
@@ -42,12 +97,14 @@ const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
42
97
  });
43
98
  }
44
99
  }, [tolgee]);
100
+ const tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);
101
+ const [loading, setLoading] = React.useState(!tolgeeSSR.isLoaded());
45
102
  const optionsWithDefault = Object.assign(Object.assign({}, DEFAULT_REACT_OPTIONS), options);
46
103
  const TolgeeProviderContext = getProviderInstance();
47
104
  if (optionsWithDefault.useSuspense) {
48
- return (React__default["default"].createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? (fallback) : (React__default["default"].createElement(React.Suspense, { fallback: fallback || null }, children))));
105
+ return (React__default["default"].createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? (fallback) : (React__default["default"].createElement(React.Suspense, { fallback: fallback || null }, children))));
49
106
  }
50
- return (React__default["default"].createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? fallback : children));
107
+ return (React__default["default"].createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? fallback : children));
51
108
  };
52
109
 
53
110
  let globalContext;
@@ -202,55 +259,6 @@ const useTolgee = (events) => {
202
259
  return tolgee;
203
260
  };
204
261
 
205
- function getTolgeeWithDeactivatedWrapper(tolgee) {
206
- return Object.assign(Object.assign({}, tolgee), { t(...args) {
207
- // @ts-ignore
208
- const props = web.getTranslateProps(...args);
209
- return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
210
- } });
211
- }
212
- /**
213
- * Updates tolgee static data and language, to be ready right away for the first render
214
- * and therefore compatible with SSR.
215
- *
216
- * It also ensures that the first render is done without wrapping and so it avoids
217
- * "client different than server" issues.
218
- *
219
- * @param tolgeeInstance initialized Tolgee instance
220
- * @param language language that is obtained outside of Tolgee on the server and client
221
- * @param staticData static data for the language
222
- */
223
- function useTolgeeSSR(tolgeeInstance, language, staticData) {
224
- const [noWrappingTolgee] = React.useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
225
- const [initialRender, setInitialRender] = React.useState(true);
226
- React.useEffect(() => {
227
- setInitialRender(false);
228
- }, []);
229
- React.useMemo(() => {
230
- // we have to prepare tolgee before rendering children
231
- // so translations are available right away
232
- // events emitting must be off, to not trigger re-render while rendering
233
- tolgeeInstance.setEmitterActive(false);
234
- tolgeeInstance.addStaticData(staticData);
235
- tolgeeInstance.changeLanguage(language);
236
- tolgeeInstance.setEmitterActive(true);
237
- }, [language, staticData, tolgeeInstance]);
238
- React.useState(() => {
239
- // running this function only on first render
240
- if (!tolgeeInstance.isLoaded()) {
241
- // warning user, that static data provided are not sufficient
242
- // for proper SSR render
243
- const missingRecords = tolgeeInstance
244
- .getRequiredRecords(language)
245
- .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
246
- .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
247
- // eslint-disable-next-line no-console
248
- console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
249
- }
250
- });
251
- return initialRender ? noWrappingTolgee : tolgeeInstance;
252
- }
253
-
254
262
  exports.GlobalContextPlugin = GlobalContextPlugin;
255
263
  exports.T = T;
256
264
  exports.TBase = TBase;
@@ -1 +1 @@
1
- {"version":3,"file":"tolgee-react.cjs.js","sources":["../src/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/useTranslate.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts","../src/useTolgeeSSR.ts"],"sourcesContent":["import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n}) => {\n const [loading, setLoading] = useState(!tolgee.isLoaded());\n\n // prevent restarting tolgee unnecesarly\n // however if the instance change on hot-reloading\n // we want to restart\n useEffect(() => {\n if (LAST_TOLGEE_INSTANCE?.run !== tolgee.run) {\n if (LAST_TOLGEE_INSTANCE) {\n LAST_TOLGEE_INSTANCE.stop();\n }\n LAST_TOLGEE_INSTANCE = tolgee;\n tolgee\n .run()\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n })\n .finally(() => {\n setLoading(false);\n });\n }\n }, [tolgee]);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n","import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n"],"names":["React","useState","useEffect","Suspense","useContext","useCallback","getFallback","getFallbackArray","useRef","getTranslateProps","useMemo"],"mappings":";;;;;;;;;;;AAIO,MAAM,qBAAqB,GAAiB;AACjD,IAAA,WAAW,EAAE,IAAI;CAClB,CAAC;AAEF,IAAI,gBAA+D,CAAC;AAE7D,MAAM,mBAAmB,GAAG,MAAK;IACtC,IAAI,CAAC,gBAAgB,EAAE;AACrB,QAAA,gBAAgB,GAAGA,yBAAK,CAAC,aAAa,CACpC,SAAS,CACV,CAAC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,EAAE,EAAE;;;YAG9B,MAAM,cAAc,GAAG,cAAc;iBAClC,kBAAkB,CAAC,QAAQ,CAAC;iBAC5B,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,KAC3B,SAAS,GAAG,CAAG,EAAA,SAAS,CAAI,CAAA,EAAA,QAAQ,EAAE,GAAG,QAAQ,CAClD;AACA,iBAAA,MAAM,CAAC,CAAC,GAAG,KAAK,EAAC,UAAU,KAAV,IAAA,IAAA,UAAU,uBAAV,UAAU,CAAG,GAAG,CAAC,CAAA,CAAC,CAAC;;YAGvC,OAAO,CAAC,IAAI,CACV,CAAyE,sEAAA,EAAA,cAAc,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK,CAAI,CAAA,EAAA,GAAG,CAAG,CAAA,CAAA,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAA,CAC9H,CAAC;AACH,SAAA;AACH,KAAC,CAAC,CAAC;IAEH,OAAO,aAAa,GAAG,gBAAgB,GAAG,cAAc,CAAC;AAC3D;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"tolgee-react.cjs.js","sources":["../src/useTolgeeSSR.ts","../src/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/useTranslate.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts"],"sourcesContent":["import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n isSSR,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * If no language data and static data are provided no action is taken\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const enabled = Boolean(language || staticData);\n\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(enabled);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n if (enabled) {\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n if (enabled && isSSR()) {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance, TolgeeStaticData } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\nimport { useTolgeeSSR } from './useTolgeeSSR';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * Hard set language to this value, use together with `staticData`\n */\n language?: string;\n /**\n * If provided, static data will be hard set to Tolgee cache for initial render\n */\n staticData?: TolgeeStaticData;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n staticData,\n language,\n}) => {\n // prevent restarting tolgee unnecesarly\n // however if the instance change on hot-reloading\n // we want to restart\n useEffect(() => {\n if (LAST_TOLGEE_INSTANCE?.run !== tolgee.run) {\n if (LAST_TOLGEE_INSTANCE) {\n LAST_TOLGEE_INSTANCE.stop();\n }\n LAST_TOLGEE_INSTANCE = tolgee;\n tolgee\n .run()\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n })\n .finally(() => {\n setLoading(false);\n });\n }\n }, [tolgee]);\n\n const tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n\n const [loading, setLoading] = useState(!tolgeeSSR.isLoaded());\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n"],"names":["getTranslateProps","useState","useEffect","useMemo","isSSR","React","Suspense","useContext","useCallback","getFallback","getFallbackArray","useRef"],"mappings":";;;;;;;;;;;AAQA,SAAS,+BAA+B,CACtC,MAAsB,EAAA;AAEtB,IAA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web");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=n(e);const s={useSuspense:!0};let o;const a=()=>(o||(o=r.default.createContext(void 0)),o);let u;let l;const c=()=>{const t=a(),n=e.useContext(t)||l;if(!n)throw new Error("Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?");return n},i=()=>{const[t,n]=e.useState(0);return{instance:t,rerender:e.useCallback((()=>{n((e=>e+1))}),[n])}},d=(n,r)=>{const{tolgee:s,options:o}=c(),a=t.getFallback(n),u=t.getFallbackArray(a).join(":"),l=Object.assign(Object.assign({},o),r),{rerender:d,instance:f}=i(),g=e.useRef(),p=e.useRef([]);p.current=[];const b=s.isLoaded(a);e.useEffect((()=>{const e=s.onNsUpdate(d);return g.current=e,e.subscribeNs(a),p.current.forEach((t=>{e.subscribeNs(t)})),()=>{e.unsubscribe()}}),[u,s]),e.useEffect((()=>(s.addActiveNs(a),()=>s.removeActiveNs(a))),[u,s]);const v=e.useCallback((e=>{var t;const n=null!==(t=e.ns)&&void 0!==t?t:null==a?void 0:a[0];return(e=>{var t;p.current.push(e),null===(t=g.current)||void 0===t||t.subscribeNs(e)})(n),s.t(Object.assign(Object.assign({},e),{ns:n}))}),[s,f]);if(l.useSuspense&&!b)throw s.addActiveNs(a,!0);return{t:v,isLoading:!b}},f=e=>{if(!e)return;const t={};return Object.entries(e||{}).forEach((([e,n])=>{if("function"==typeof n)t[e]=e=>n(g(e));else if(r.default.isValidElement(n)){const s=n;t[e]=e=>void 0===s.props.children&&(null==e?void 0:e.length)?r.default.cloneElement(s,{},g(e)):r.default.cloneElement(s)}else t[e]=n})),t},g=e=>Array.isArray(e)?r.default.Children.toArray(e):e,p=e=>{const t=e.keyName||e.children;void 0===t&&console.error("T component: keyName not defined");const n=e.defaultValue||(e.keyName?e.children:void 0),s=g(e.t({key:t,params:f(e.params),defaultValue:n,noWrap:e.noWrap,ns:e.ns,language:e.language}));return r.default.createElement(r.default.Fragment,null,s)};exports.GlobalContextPlugin=e=>t=>(l={tolgee:t,options:Object.assign(Object.assign({},s),e)},t),exports.T=e=>{const{t:t}=d();return r.default.createElement(p,Object.assign({t:t},e))},exports.TBase=p,exports.TolgeeProvider=({tolgee:t,options:n,children:o,fallback:l})=>{const[c,i]=e.useState(!t.isLoaded());e.useEffect((()=>{(null==u?void 0:u.run)!==t.run&&(u&&u.stop(),u=t,t.run().catch((e=>{console.error(e)})).finally((()=>{i(!1)})))}),[t]);const d=Object.assign(Object.assign({},s),n),f=a();return d.useSuspense?r.default.createElement(f.Provider,{value:{tolgee:t,options:d}},c?l:r.default.createElement(e.Suspense,{fallback:l||null},o)):r.default.createElement(f.Provider,{value:{tolgee:t,options:d}},c?l:o)},exports.getProviderInstance=a,exports.useTolgee=t=>{const{tolgee:n}=c(),{rerender:r}=i();return e.useEffect((()=>{const e=null==t?void 0:t.map((e=>n.on(e,r)));return()=>{null==e||e.forEach((e=>e.unsubscribe()))}}),[null==t?void 0:t.join(":")]),n},exports.useTolgeeSSR=function(n,r,s){const[o]=e.useState((()=>{return e=n,Object.assign(Object.assign({},e),{t(...n){const r=t.getTranslateProps(...n);return e.t(Object.assign(Object.assign({},r),{noWrap:!0}))}});var e})),[a,u]=e.useState(!0);return e.useEffect((()=>{u(!1)}),[]),e.useMemo((()=>{n.setEmitterActive(!1),n.addStaticData(s),n.changeLanguage(r),n.setEmitterActive(!0)}),[r,s,n]),e.useState((()=>{if(!n.isLoaded()){const e=n.getRequiredRecords(r).map((({namespace:e,language:t})=>e?`${e}:${t}`:t)).filter((e=>!(null==s?void 0:s[e])));console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${e.map((e=>`"${e}"`)).join(", ")}`)}})),a?o:n},exports.useTranslate=(n,r)=>{const{t:s,isLoading:o}=d(n,r);return{t:e.useCallback(((...e)=>{const n=t.getTranslateProps(...e);return s(n)}),[s]),isLoading:o}},Object.keys(t).forEach((function(e){"default"===e||exports.hasOwnProperty(e)||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}})}));
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@tolgee/web");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=n(e);function s(n,r,s){const o=Boolean(r||s),[a]=e.useState((()=>{return e=n,Object.assign(Object.assign({},e),{t(...n){const r=t.getTranslateProps(...n);return e.t(Object.assign(Object.assign({},r),{noWrap:!0}))}});var e})),[u,l]=e.useState(o);return e.useEffect((()=>{l(!1)}),[]),e.useMemo((()=>{o&&(n.setEmitterActive(!1),n.addStaticData(s),n.changeLanguage(r),n.setEmitterActive(!0))}),[r,s,n]),e.useState((()=>{if(o&&t.isSSR()&&!n.isLoaded()){const e=n.getRequiredRecords(r).map((({namespace:e,language:t})=>e?`${e}:${t}`:t)).filter((e=>!(null==s?void 0:s[e])));console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${e.map((e=>`"${e}"`)).join(", ")}`)}})),u?a:n}const o={useSuspense:!0};let a;const u=()=>(a||(a=r.default.createContext(void 0)),a);let l;let c;const i=()=>{const t=u(),n=e.useContext(t)||c;if(!n)throw new Error("Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?");return n},d=()=>{const[t,n]=e.useState(0);return{instance:t,rerender:e.useCallback((()=>{n((e=>e+1))}),[n])}},f=(n,r)=>{const{tolgee:s,options:o}=i(),a=t.getFallback(n),u=t.getFallbackArray(a).join(":"),l=Object.assign(Object.assign({},o),r),{rerender:c,instance:f}=d(),g=e.useRef(),p=e.useRef([]);p.current=[];const b=s.isLoaded(a);e.useEffect((()=>{const e=s.onNsUpdate(c);return g.current=e,e.subscribeNs(a),p.current.forEach((t=>{e.subscribeNs(t)})),()=>{e.unsubscribe()}}),[u,s]),e.useEffect((()=>(s.addActiveNs(a),()=>s.removeActiveNs(a))),[u,s]);const v=e.useCallback((e=>{var t;const n=null!==(t=e.ns)&&void 0!==t?t:null==a?void 0:a[0];return(e=>{var t;p.current.push(e),null===(t=g.current)||void 0===t||t.subscribeNs(e)})(n),s.t(Object.assign(Object.assign({},e),{ns:n}))}),[s,f]);if(l.useSuspense&&!b)throw s.addActiveNs(a,!0);return{t:v,isLoading:!b}},g=e=>{if(!e)return;const t={};return Object.entries(e||{}).forEach((([e,n])=>{if("function"==typeof n)t[e]=e=>n(p(e));else if(r.default.isValidElement(n)){const s=n;t[e]=e=>void 0===s.props.children&&(null==e?void 0:e.length)?r.default.cloneElement(s,{},p(e)):r.default.cloneElement(s)}else t[e]=n})),t},p=e=>Array.isArray(e)?r.default.Children.toArray(e):e,b=e=>{const t=e.keyName||e.children;void 0===t&&console.error("T component: keyName not defined");const n=e.defaultValue||(e.keyName?e.children:void 0),s=p(e.t({key:t,params:g(e.params),defaultValue:n,noWrap:e.noWrap,ns:e.ns,language:e.language}));return r.default.createElement(r.default.Fragment,null,s)};exports.GlobalContextPlugin=e=>t=>(c={tolgee:t,options:Object.assign(Object.assign({},o),e)},t),exports.T=e=>{const{t:t}=f();return r.default.createElement(b,Object.assign({t:t},e))},exports.TBase=b,exports.TolgeeProvider=({tolgee:t,options:n,children:a,fallback:c,staticData:i,language:d})=>{e.useEffect((()=>{(null==l?void 0:l.run)!==t.run&&(l&&l.stop(),l=t,t.run().catch((e=>{console.error(e)})).finally((()=>{p(!1)})))}),[t]);const f=s(t,d,i),[g,p]=e.useState(!f.isLoaded()),b=Object.assign(Object.assign({},o),n),v=u();return b.useSuspense?r.default.createElement(v.Provider,{value:{tolgee:f,options:b}},g?c:r.default.createElement(e.Suspense,{fallback:c||null},a)):r.default.createElement(v.Provider,{value:{tolgee:f,options:b}},g?c:a)},exports.getProviderInstance=u,exports.useTolgee=t=>{const{tolgee:n}=i(),{rerender:r}=d();return e.useEffect((()=>{const e=null==t?void 0:t.map((e=>n.on(e,r)));return()=>{null==e||e.forEach((e=>e.unsubscribe()))}}),[null==t?void 0:t.join(":")]),n},exports.useTolgeeSSR=s,exports.useTranslate=(n,r)=>{const{t:s,isLoading:o}=f(n,r);return{t:e.useCallback(((...e)=>{const n=t.getTranslateProps(...e);return s(n)}),[s]),isLoading:o}},Object.keys(t).forEach((function(e){"default"===e||exports.hasOwnProperty(e)||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}})}));
2
2
  //# sourceMappingURL=tolgee-react.cjs.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tolgee-react.cjs.min.js","sources":["../src/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts","../src/useTolgeeSSR.ts","../src/useTranslate.ts"],"sourcesContent":["import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n}) => {\n const [loading, setLoading] = useState(!tolgee.isLoaded());\n\n // prevent restarting tolgee unnecesarly\n // however if the instance change on hot-reloading\n // we want to restart\n useEffect(() => {\n if (LAST_TOLGEE_INSTANCE?.run !== tolgee.run) {\n if (LAST_TOLGEE_INSTANCE) {\n LAST_TOLGEE_INSTANCE.stop();\n }\n LAST_TOLGEE_INSTANCE = tolgee;\n tolgee\n .run()\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n })\n .finally(() => {\n setLoading(false);\n });\n }\n }, [tolgee]);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n","import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n"],"names":["DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","globalContext","useTolgeeContext","TolgeeProviderContext","context","useContext","Error","useRerender","instance","setCounter","useState","rerender","useCallback","num","useTranslateInternal","ns","options","tolgee","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","join","currentOptions","Object","assign","subscriptionRef","useRef","subscriptionQueue","current","isLoaded","useEffect","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","t","props","fallbackNs","_a","push","subscribeToNs","isLoading","wrapTagHandlers","params","result","entries","key","value","chunk","addReactKeys","isValidElement","el","children","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","console","error","defaultValue","translation","noWrap","language","createElement","Fragment","fallback","loading","setLoading","run","stop","catch","e","finally","optionsWithDefault","Provider","Suspense","events","listeners","map","on","listener","tolgeeInstance","staticData","noWrappingTolgee","getTolgeeWithDeactivatedWrapper","args","getTranslateProps","initialRender","setInitialRender","useMemo","setEmitterActive","addStaticData","changeLanguage","missingRecords","getRequiredRecords","namespace","filter","warn","tInternal"],"mappings":"uMAIO,MAAMA,EAAsC,CACjDC,aAAa,GAGf,IAAIC,EAEG,MAAMC,EAAsB,KAC5BD,IACHA,EAAmBE,EAAK,QAACC,mBACvBC,IAIGJ,GAGT,IAAIK,EChBJ,IAAIC,ECAG,MAAMC,EAAmB,KAC9B,MAAMC,EAAwBP,IACxBQ,EAAUC,EAAUA,WAACF,IDWpBF,ECVP,I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,GAEH,MAAMtD,EAAQuD,EAAAA,qBAAqBD,GACnC,OAAO9E,EAAOuB,EAAOf,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAe,IAAO8B,QAAQ,IACrC,IATL,IACEtD,CA6BiD,KAG1CgF,EAAeC,GAAoBxF,EAAQA,UAAC,GAmCnD,OAjCAsB,EAAAA,WAAU,KACRkE,GAAiB,EAAM,GACtB,IAEHC,EAAAA,SAAQ,KAINR,EAAeS,kBAAiB,GAChCT,EAAeU,cAAcT,GAC7BD,EAAeW,eAAe9B,GAC9BmB,EAAeS,kBAAiB,EAAK,GACpC,CAAC5B,EAAUoB,EAAYD,IAE1BjF,EAAAA,UAAS,KAEP,IAAKiF,EAAe5D,WAAY,CAG9B,MAAMwE,EAAiBZ,EACpBa,mBAAmBhC,GACnBgB,KAAI,EAAGiB,YAAWjC,cACjBiC,EAAY,GAAGA,KAAajC,IAAaA,IAE1CkC,QAAQvD,KAASyC,eAAAA,EAAazC,MAGjCgB,QAAQwC,KACN,yEAAyEJ,EAAef,KAAKrC,GAAQ,IAAIA,OAAQ5B,KAAK,QAEzH,KAGI0E,EAAgBJ,EAAmBF,CAC5C,uBC5D4B,CAC1B5E,EACAC,KAEA,MAAQwB,EAAGoE,EAAS9D,UAAEA,GAAchC,EAAqBC,EAAIC,GAW7D,MAAO,CAAEwB,EATC5B,EAAAA,aACR,IAAIoC,KAEF,MAAMP,EAAQuD,EAAAA,qBAAqBhD,GACnC,OAAO4D,EAAUnE,EAAM,GAEzB,CAACmE,IAGS9D,YAAW"}
1
+ {"version":3,"file":"tolgee-react.cjs.min.js","sources":["../src/useTolgeeSSR.ts","../src/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts","../src/useTranslate.ts"],"sourcesContent":["import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n isSSR,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * If no language data and static data are provided no action is taken\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const enabled = Boolean(language || staticData);\n\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(enabled);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n if (enabled) {\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n if (enabled && isSSR()) {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance, TolgeeStaticData } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\nimport { useTolgeeSSR } from './useTolgeeSSR';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * Hard set language to this value, use together with `staticData`\n */\n language?: string;\n /**\n * If provided, static data will be hard set to Tolgee cache for initial render\n */\n staticData?: TolgeeStaticData;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n staticData,\n language,\n}) => {\n // prevent restarting tolgee unnecesarly\n // however if the instance change on hot-reloading\n // we want to restart\n useEffect(() => {\n if (LAST_TOLGEE_INSTANCE?.run !== tolgee.run) {\n if (LAST_TOLGEE_INSTANCE) {\n LAST_TOLGEE_INSTANCE.stop();\n }\n LAST_TOLGEE_INSTANCE = tolgee;\n tolgee\n .run()\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n })\n .finally(() => {\n setLoading(false);\n });\n }\n }, [tolgee]);\n\n const tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n\n const [loading, setLoading] = useState(!tolgeeSSR.isLoaded());\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n"],"names":["useTolgeeSSR","tolgeeInstance","language","staticData","enabled","Boolean","noWrappingTolgee","useState","getTolgeeWithDeactivatedWrapper","tolgee","Object","assign","t","args","props","getTranslateProps","noWrap","initialRender","setInitialRender","useEffect","useMemo","setEmitterActive","addStaticData","changeLanguage","isSSR","isLoaded","missingRecords","getRequiredRecords","map","namespace","filter","key","console","warn","join","DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","globalContext","useTolgeeContext","TolgeeProviderContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","options","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","fallbackNs","_a","push","subscribeToNs","isLoading","wrapTagHandlers","params","result","entries","value","chunk","addReactKeys","isValidElement","el","children","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","error","defaultValue","translation","createElement","Fragment","fallback","run","stop","catch","e","finally","setLoading","tolgeeSSR","loading","optionsWithDefault","Provider","Suspense","events","listeners","on","listener","tInternal"],"mappings":"gNAkCgBA,EACdC,EACAC,EACAC,GAEA,MAAMC,EAAUC,QAAQH,GAAYC,IAE7BG,GAAoBC,EAAAA,UAAS,KAClCC,OAjCFC,EAiCkCR,EA/BlCS,OAAAC,OAAAD,OAAAC,OAAA,GACKF,GAAM,CACT,CAAAG,IAAKC,GAEH,MAAMC,EAAQC,EAAAA,qBAAqBF,GACnC,OAAOJ,EAAOG,EAAOF,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAG,IAAOE,QAAQ,IACrC,IATL,IACEP,CAiCi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,IAE1C6G,EAASF,GAAcvG,EAAQA,UAAEwG,EAAUtF,YAE5CwF,EAA0BvG,OAAAC,OAAAD,OAAAC,OAAA,GAAAwB,GAA0BsB,GAEpDZ,EAAwBP,IAE9B,OAAI2E,EAAmB7E,YAEnBG,UAAC+D,cAAAzD,EAAsBqE,SAAQ,CAC7B9B,MAAO,CAAE3E,OAAQsG,EAAWtD,QAASwD,IAEpCD,EAAO,EAGNzE,EAAAA,QAAA+D,cAACa,WAAS,CAAAX,SAAUA,GAAY,MAAOf,IAO7ClD,EAAAA,QAAA+D,cAACzD,EAAsBqE,SAAQ,CAC7B9B,MAAO,CAAE3E,OAAQsG,EAAWtD,QAASwD,IAEpCD,EAAUR,EAAWf,EAExB,kDQ1FsB2B,IACxB,MAAM3G,OAAEA,GAAWmC,KAEbQ,SAAEA,GAAaH,IASrB,OAPA9B,EAAAA,WAAU,KACR,MAAMkG,EAAYD,eAAAA,EAAQxF,KAAKgF,GAAMnG,EAAO6G,GAAGV,EAAGxD,KAClD,MAAO,KACLiE,SAAAA,EAAW9C,SAASgD,GAAaA,EAAS/C,eAAc,CACzD,GACA,CAAC4C,aAAA,EAAAA,EAAQlF,KAAK,OAEVzB,CAAM,8CCDa,CAC1B+C,EACAC,KAEA,MAAQ7C,EAAG4G,EAASzC,UAAEA,GAAcxB,EAAqBC,EAAIC,GAW7D,MAAO,CAAE7C,EATCyC,EAAAA,aACR,IAAI4B,KAEF,MAAMnE,EAAQC,EAAAA,qBAAqBkE,GACnC,OAAOuC,EAAU1G,EAAM,GAEzB,CAAC0G,IAGSzC,YAAW"}
@@ -1,7 +1,63 @@
1
- import React, { useState, useEffect, Suspense, useContext, useCallback, useRef, useMemo } from 'react';
2
- import { getFallback, getFallbackArray, getTranslateProps } from '@tolgee/web';
1
+ import React, { useState, useEffect, useMemo, Suspense, useContext, useCallback, useRef } from 'react';
2
+ import { isSSR, getTranslateProps, getFallback, getFallbackArray } from '@tolgee/web';
3
3
  export * from '@tolgee/web';
4
4
 
5
+ function getTolgeeWithDeactivatedWrapper(tolgee) {
6
+ return Object.assign(Object.assign({}, tolgee), { t(...args) {
7
+ // @ts-ignore
8
+ const props = getTranslateProps(...args);
9
+ return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
10
+ } });
11
+ }
12
+ /**
13
+ * Updates tolgee static data and language, to be ready right away for the first render
14
+ * and therefore compatible with SSR.
15
+ *
16
+ * It also ensures that the first render is done without wrapping and so it avoids
17
+ * "client different than server" issues.
18
+ *
19
+ * If no language data and static data are provided no action is taken
20
+ *
21
+ * @param tolgeeInstance initialized Tolgee instance
22
+ * @param language language that is obtained outside of Tolgee on the server and client
23
+ * @param staticData static data for the language
24
+ */
25
+ function useTolgeeSSR(tolgeeInstance, language, staticData) {
26
+ const enabled = Boolean(language || staticData);
27
+ const [noWrappingTolgee] = useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
28
+ const [initialRender, setInitialRender] = useState(enabled);
29
+ useEffect(() => {
30
+ setInitialRender(false);
31
+ }, []);
32
+ useMemo(() => {
33
+ // we have to prepare tolgee before rendering children
34
+ // so translations are available right away
35
+ // events emitting must be off, to not trigger re-render while rendering
36
+ if (enabled) {
37
+ tolgeeInstance.setEmitterActive(false);
38
+ tolgeeInstance.addStaticData(staticData);
39
+ tolgeeInstance.changeLanguage(language);
40
+ tolgeeInstance.setEmitterActive(true);
41
+ }
42
+ }, [language, staticData, tolgeeInstance]);
43
+ useState(() => {
44
+ if (enabled && isSSR()) {
45
+ // running this function only on first render
46
+ if (!tolgeeInstance.isLoaded()) {
47
+ // warning user, that static data provided are not sufficient
48
+ // for proper SSR render
49
+ const missingRecords = tolgeeInstance
50
+ .getRequiredRecords(language)
51
+ .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
52
+ .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
53
+ // eslint-disable-next-line no-console
54
+ console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
55
+ }
56
+ }
57
+ });
58
+ return initialRender ? noWrappingTolgee : tolgeeInstance;
59
+ }
60
+
5
61
  const DEFAULT_REACT_OPTIONS = {
6
62
  useSuspense: true,
7
63
  };
@@ -13,8 +69,7 @@ const getProviderInstance = () => {
13
69
  return ProviderInstance;
14
70
  };
15
71
  let LAST_TOLGEE_INSTANCE = undefined;
16
- const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
17
- const [loading, setLoading] = useState(!tolgee.isLoaded());
72
+ const TolgeeProvider = ({ tolgee, options, children, fallback, staticData, language, }) => {
18
73
  // prevent restarting tolgee unnecesarly
19
74
  // however if the instance change on hot-reloading
20
75
  // we want to restart
@@ -35,12 +90,14 @@ const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
35
90
  });
36
91
  }
37
92
  }, [tolgee]);
93
+ const tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);
94
+ const [loading, setLoading] = useState(!tolgeeSSR.isLoaded());
38
95
  const optionsWithDefault = Object.assign(Object.assign({}, DEFAULT_REACT_OPTIONS), options);
39
96
  const TolgeeProviderContext = getProviderInstance();
40
97
  if (optionsWithDefault.useSuspense) {
41
- return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? (fallback) : (React.createElement(Suspense, { fallback: fallback || null }, children))));
98
+ return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? (fallback) : (React.createElement(Suspense, { fallback: fallback || null }, children))));
42
99
  }
43
- return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? fallback : children));
100
+ return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? fallback : children));
44
101
  };
45
102
 
46
103
  let globalContext;
@@ -195,54 +252,5 @@ const useTolgee = (events) => {
195
252
  return tolgee;
196
253
  };
197
254
 
198
- function getTolgeeWithDeactivatedWrapper(tolgee) {
199
- return Object.assign(Object.assign({}, tolgee), { t(...args) {
200
- // @ts-ignore
201
- const props = getTranslateProps(...args);
202
- return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
203
- } });
204
- }
205
- /**
206
- * Updates tolgee static data and language, to be ready right away for the first render
207
- * and therefore compatible with SSR.
208
- *
209
- * It also ensures that the first render is done without wrapping and so it avoids
210
- * "client different than server" issues.
211
- *
212
- * @param tolgeeInstance initialized Tolgee instance
213
- * @param language language that is obtained outside of Tolgee on the server and client
214
- * @param staticData static data for the language
215
- */
216
- function useTolgeeSSR(tolgeeInstance, language, staticData) {
217
- const [noWrappingTolgee] = useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
218
- const [initialRender, setInitialRender] = useState(true);
219
- useEffect(() => {
220
- setInitialRender(false);
221
- }, []);
222
- useMemo(() => {
223
- // we have to prepare tolgee before rendering children
224
- // so translations are available right away
225
- // events emitting must be off, to not trigger re-render while rendering
226
- tolgeeInstance.setEmitterActive(false);
227
- tolgeeInstance.addStaticData(staticData);
228
- tolgeeInstance.changeLanguage(language);
229
- tolgeeInstance.setEmitterActive(true);
230
- }, [language, staticData, tolgeeInstance]);
231
- useState(() => {
232
- // running this function only on first render
233
- if (!tolgeeInstance.isLoaded()) {
234
- // warning user, that static data provided are not sufficient
235
- // for proper SSR render
236
- const missingRecords = tolgeeInstance
237
- .getRequiredRecords(language)
238
- .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
239
- .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
240
- // eslint-disable-next-line no-console
241
- console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
242
- }
243
- });
244
- return initialRender ? noWrappingTolgee : tolgeeInstance;
245
- }
246
-
247
255
  export { GlobalContextPlugin, T, TBase, TolgeeProvider, getProviderInstance, useTolgee, useTolgeeSSR, useTranslate };
248
256
  //# sourceMappingURL=tolgee-react.esm.js.map