@tolgee/react 5.29.6-prerelease.fc7efe8f.0 → 5.30.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/dist/TolgeeProvider.d.ts +16 -5
- package/dist/tolgee-react.cjs.js +20 -22
- package/dist/tolgee-react.cjs.js.map +1 -1
- package/dist/tolgee-react.cjs.min.js +1 -1
- package/dist/tolgee-react.cjs.min.js.map +1 -1
- package/dist/tolgee-react.esm.js +21 -23
- package/dist/tolgee-react.esm.js.map +1 -1
- package/dist/tolgee-react.esm.min.js +1 -1
- package/dist/tolgee-react.esm.min.js.map +1 -1
- package/dist/tolgee-react.esm.min.mjs +1 -1
- package/dist/tolgee-react.esm.min.mjs.map +1 -1
- package/dist/tolgee-react.esm.mjs +21 -23
- package/dist/tolgee-react.esm.mjs.map +1 -1
- package/dist/tolgee-react.umd.js +20 -22
- package/dist/tolgee-react.umd.js.map +1 -1
- package/dist/tolgee-react.umd.min.js +1 -1
- package/dist/tolgee-react.umd.min.js.map +1 -1
- package/dist/useTolgeeSSR.d.ts +3 -4
- package/lib/TolgeeProvider.d.ts +16 -5
- package/lib/useTolgeeSSR.d.ts +3 -4
- package/package.json +5 -5
- package/src/TolgeeProvider.tsx +24 -8
- package/src/useTolgeeSSR.ts +21 -26
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tolgee-react.esm.min.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":["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","TolgeeProvider","options","children","fallback","run","stop","catch","e","error","finally","setLoading","tolgeeSSR","loading","optionsWithDefault","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","wrapTagHandlers","result","entries","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","Fragment","T","useTolgee","events","listeners","on","listener"],"mappings":"+PAkCgBA,EACdC,EACAC,EACAC,GAEA,MAAMC,EAAUC,QAAQH,GAAYC,IAE7BG,GAAoBC,GAAS,KAClCC,OAjCFC,EAiCkCR,EA/BlCS,OAAAC,OAAAD,OAAAC,OAAA,GACKF,GAAM,CACT,CAAAG,IAAKC,GAEH,MAAMC,EAAQC,KAAqBF,GACnC,OAAOJ,EAAOG,EAAOF,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAG,IAAOE,QAAQ,IACrC,IATL,IACEP,CAiCiD,KAG1CQ,EAAeC,GAAoBX,EAASH,GAuCnD,OArCAe,GAAU,KACRD,GAAiB,EAAM,GACtB,IAEHE,GAAQ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WtG,EAAM+B,cAC7CJ,IAARV,GAEFC,QAAQmB,MAAM,oCAEhB,MAAMkE,EACJvG,EAAMuG,eACJvG,EAA2BsG,QAAUtG,EAAM+B,cAAWJ,GAEpD6E,EAAcb,EAClB3F,EAAMF,EAAE,CACNmB,IAAKA,EACLqE,OAAQC,EAAgBvF,EAAMsF,QAC9BiB,eACArG,OAAQF,EAAME,OACd2D,GAAI7D,EAAM6D,GACVzE,SAAUY,EAAMZ,YAIpB,OAAOqC,EAAAmB,cAAAnB,EAAAgF,SAAA,KAAGD,EAAe,ECddE,EAAiB1G,IAC5B,MAAMF,EAAEA,GAAM8D,IAEd,OAAOnC,EAAAmB,cAACyD,EAAMzG,OAAAC,OAAA,CAAAC,EAAGA,GAA8BE,GAAS,ECT7C2G,EAAaC,IACxB,MAAMjH,OAAEA,GAAWuD,KAEbO,SAAEA,GAAaH,IASrB,OAPAjD,GAAU,KACR,MAAMwG,EAAYD,eAAAA,EAAQ9F,KAAKsB,GAAMzC,EAAOmH,GAAG1E,EAAGqB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQxF,KAAK,OAEVzB,CAAM"}
|
|
1
|
+
{"version":3,"file":"tolgee-react.esm.min.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} 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 * @param enabled if set to false, no action is taken\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined,\n enabled = true\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 if (enabled) {\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 }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded() && enabled) {\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 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 type SSROptions = {\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 interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * use this option if you use SSR\n *\n * You can pass staticData and language\n * which will be set to tolgee instance for the initial render\n *\n * Don't switch between ssr and non-ssr dynamically\n */\n ssr?: SSROptions | boolean;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n ssr,\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 let tolgeeSSR = tolgee;\n\n const { language, staticData } = (\n typeof ssr !== 'object' ? {} : ssr\n ) as SSROptions;\n tolgeeSSR = useTolgeeSSR(tolgee, language, staticData, Boolean(ssr));\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":["useTolgeeSSR","tolgeeInstance","language","staticData","enabled","noWrappingTolgee","useState","getTolgeeWithDeactivatedWrapper","tolgee","Object","assign","t","args","props","getTranslateProps","noWrap","initialRender","setInitialRender","useEffect","useMemo","setEmitterActive","addStaticData","changeLanguage","isLoaded","missingRecords","getRequiredRecords","map","namespace","filter","key","console","warn","join","DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","TolgeeProvider","options","children","fallback","ssr","run","stop","catch","e","error","finally","setLoading","tolgeeSSR","Boolean","loading","optionsWithDefault","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","wrapTagHandlers","result","entries","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","Fragment","T","useTolgee","events","listeners","on","listener"],"mappings":"2OAgCM,SAAUA,EACdC,EACAC,EACAC,EACAC,GAAU,GAEV,MAAOC,GAAoBC,GAAS,KAClCC,OA/BFC,EA+BkCP,EA7BlCQ,OAAAC,OAAAD,OAAAC,OAAA,GACKF,GAAM,CACT,CAAAG,IAAKC,GAEH,MAAMC,EAAQC,KAAqBF,GACnC,OAAOJ,EAAOG,EAAOF,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAG,IAAOE,QAAQ,IACrC,IATL,IACEP,CA+Bi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AaF,EAE1B,MACCL,EAAOzE,GAAO+B,CACf,IAGI0C,CAAM,EAGFG,EACXK,GAEIC,MAAMC,QAAQF,GACTzE,EAAM4E,SAASC,QAAQJ,GAEvBA,ECpCEK,EAAyBtG,IACpC,MAAMgB,EAAOhB,EAA2BuG,SAAWvG,EAAM8B,cAC7CJ,IAARV,GAEFC,QAAQoB,MAAM,oCAEhB,MAAMmE,EACJxG,EAAMwG,eACJxG,EAA2BuG,QAAUvG,EAAM8B,cAAWJ,GAEpD+E,EAAcb,EAClB5F,EAAMF,EAAE,CACNkB,IAAKA,EACLuE,OAAQC,EAAgBxF,EAAMuF,QAC9BiB,eACAtG,OAAQF,EAAME,OACd4D,GAAI9D,EAAM8D,GACVzE,SAAUW,EAAMX,YAIpB,OAAOmC,EAAAqB,cAAArB,EAAAkF,SAAA,KAAGD,EAAe,ECddE,EAAiB3G,IAC5B,MAAMF,EAAEA,GAAM+D,IAEd,OAAOrC,EAAAqB,cAACyD,EAAM1G,OAAAC,OAAA,CAAAC,EAAGA,GAA8BE,GAAS,ECT7C4G,EAAaC,IACxB,MAAMlH,OAAEA,GAAWwD,KAEbO,SAAEA,GAAaH,IASrB,OAPAlD,GAAU,KACR,MAAMyG,EAAYD,eAAAA,EAAQhG,KAAKuB,GAAMzC,EAAOoH,GAAG3E,EAAGsB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQ1F,KAAK,OAEVxB,CAAM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{useState as
|
|
1
|
+
import e,{useState as t,useEffect as n,useMemo as r,Suspense as o,useContext as s,useCallback as a,useRef as c}from"react";import{getTranslateProps as i,getFallback as l,getFallbackArray as u}from"@tolgee/web";export*from"@tolgee/web";function d(e,o,s,a=!0){const[c]=t((()=>{return t=e,Object.assign(Object.assign({},t),{t(...e){const n=i(...e);return t.t(Object.assign(Object.assign({},n),{noWrap:!0}))}});var t})),[l,u]=t(a);return n((()=>{u(!1)}),[]),r((()=>{a&&(e.setEmitterActive(!1),e.addStaticData(s),e.changeLanguage(o),e.setEmitterActive(!0))}),[o,s,e]),t((()=>{if(!e.isLoaded()&&a){const t=e.getRequiredRecords(o).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: ${t.map((e=>`"${e}"`)).join(", ")}`)}})),l?c:e}const g={useSuspense:!0};let p;const b=()=>(p||(p=e.createContext(void 0)),p);let f;const m=({tolgee:r,options:s,children:a,fallback:c,ssr:i})=>{n((()=>{(null==f?void 0:f.run)!==r.run&&(f&&f.stop(),f=r,r.run().catch((e=>{console.error(e)})).finally((()=>{v(!1)})))}),[r]);let l=r;const{language:u,staticData:p}="object"!=typeof i?{}:i;l=d(r,u,p,Boolean(i));const[m,v]=t(!l.isLoaded()),j=Object.assign(Object.assign({},g),s),h=b();return j.useSuspense?e.createElement(h.Provider,{value:{tolgee:l,options:j}},m?c:e.createElement(o,{fallback:c||null},a)):e.createElement(h.Provider,{value:{tolgee:l,options:j}},m?c:a)};let v;const j=e=>t=>(v={tolgee:t,options:Object.assign(Object.assign({},g),e)},t);const h=()=>{const e=b(),t=s(e)||v;if(!t)throw new Error("Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?");return t},E=()=>{const[e,n]=t(0);return{instance:e,rerender:a((()=>{n((e=>e+1))}),[n])}},O=(e,t)=>{const{tolgee:r,options:o}=h(),s=l(e),i=u(s).join(":"),d=Object.assign(Object.assign({},o),t),{rerender:g,instance:p}=E(),b=c(),f=c([]);f.current=[];const m=r.isLoaded(s);n((()=>{const e=r.onNsUpdate(g);return b.current=e,e.subscribeNs(s),f.current.forEach((t=>{e.subscribeNs(t)})),()=>{e.unsubscribe()}}),[i,r]),n((()=>(r.addActiveNs(s),()=>r.removeActiveNs(s))),[i,r]);const v=a((e=>{var t;const n=null!==(t=e.ns)&&void 0!==t?t:null==s?void 0:s[0];return(e=>{var t;f.current.push(e),null===(t=b.current)||void 0===t||t.subscribeNs(e)})(n),r.t(Object.assign(Object.assign({},e),{ns:n}))}),[r,p]);if(d.useSuspense&&!m)throw r.addActiveNs(s,!0);return{t:v,isLoading:!m}},y=(e,t)=>{const{t:n,isLoading:r}=O(e,t);return{t:a(((...e)=>{const t=i(...e);return n(t)}),[n]),isLoading:r}},N=t=>{if(!t)return;const n={};return Object.entries(t||{}).forEach((([t,r])=>{if("function"==typeof r)n[t]=e=>r(A(e));else if(e.isValidElement(r)){const o=r;n[t]=t=>void 0===o.props.children&&(null==t?void 0:t.length)?e.cloneElement(o,{},A(t)):e.cloneElement(o)}else n[t]=r})),n},A=t=>Array.isArray(t)?e.Children.toArray(t):t,L=t=>{const n=t.keyName||t.children;void 0===n&&console.error("T component: keyName not defined");const r=t.defaultValue||(t.keyName?t.children:void 0),o=A(t.t({key:n,params:N(t.params),defaultValue:r,noWrap:t.noWrap,ns:t.ns,language:t.language}));return e.createElement(e.Fragment,null,o)},k=t=>{const{t:n}=O();return e.createElement(L,Object.assign({t:n},t))},w=e=>{const{tolgee:t}=h(),{rerender:r}=E();return n((()=>{const n=null==e?void 0:e.map((e=>t.on(e,r)));return()=>{null==n||n.forEach((e=>e.unsubscribe()))}}),[null==e?void 0:e.join(":")]),t};export{j as GlobalContextPlugin,k as T,L as TBase,m as TolgeeProvider,b as getProviderInstance,w as useTolgee,d as useTolgeeSSR,y as useTranslate};
|
|
2
2
|
//# sourceMappingURL=tolgee-react.esm.min.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tolgee-react.esm.min.mjs","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":["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","TolgeeProvider","options","children","fallback","run","stop","catch","e","error","finally","setLoading","tolgeeSSR","loading","optionsWithDefault","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","wrapTagHandlers","result","entries","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","Fragment","T","useTolgee","events","listeners","on","listener"],"mappings":"+PAkCgBA,EACdC,EACAC,EACAC,GAEA,MAAMC,EAAUC,QAAQH,GAAYC,IAE7BG,GAAoBC,GAAS,KAClCC,OAjCFC,EAiCkCR,EA/BlCS,OAAAC,OAAAD,OAAAC,OAAA,GACKF,GAAM,CACT,CAAAG,IAAKC,GAEH,MAAMC,EAAQC,KAAqBF,GACnC,OAAOJ,EAAOG,EAAOF,OAAAC,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EAAOvE,GAAO6B,CACf,IAGI0C,CAAM,EAGFG,EACXK,GAEIC,MAAMC,QAAQF,GACTvE,EAAM0E,SAASC,QAAQJ,GAEvBA,ECpCEK,EAAyBrG,IACpC,MAAMiB,EAAOjB,EAA2BsG,SAAWtG,EAAM+B,cAC7CJ,IAARV,GAEFC,QAAQmB,MAAM,oCAEhB,MAAMkE,EACJvG,EAAMuG,eACJvG,EAA2BsG,QAAUtG,EAAM+B,cAAWJ,GAEpD6E,EAAcb,EAClB3F,EAAMF,EAAE,CACNmB,IAAKA,EACLqE,OAAQC,EAAgBvF,EAAMsF,QAC9BiB,eACArG,OAAQF,EAAME,OACd2D,GAAI7D,EAAM6D,GACVzE,SAAUY,EAAMZ,YAIpB,OAAOqC,EAAAmB,cAAAnB,EAAAgF,SAAA,KAAGD,EAAe,ECddE,EAAiB1G,IAC5B,MAAMF,EAAEA,GAAM8D,IAEd,OAAOnC,EAAAmB,cAACyD,EAAMzG,OAAAC,OAAA,CAAAC,EAAGA,GAA8BE,GAAS,ECT7C2G,EAAaC,IACxB,MAAMjH,OAAEA,GAAWuD,KAEbO,SAAEA,GAAaH,IASrB,OAPAjD,GAAU,KACR,MAAMwG,EAAYD,eAAAA,EAAQ9F,KAAKsB,GAAMzC,EAAOmH,GAAG1E,EAAGqB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQxF,KAAK,OAEVzB,CAAM"}
|
|
1
|
+
{"version":3,"file":"tolgee-react.esm.min.mjs","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} 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 * @param enabled if set to false, no action is taken\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined,\n enabled = true\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 if (enabled) {\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 }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded() && enabled) {\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 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 type SSROptions = {\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 interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * use this option if you use SSR\n *\n * You can pass staticData and language\n * which will be set to tolgee instance for the initial render\n *\n * Don't switch between ssr and non-ssr dynamically\n */\n ssr?: SSROptions | boolean;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n ssr,\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 let tolgeeSSR = tolgee;\n\n const { language, staticData } = (\n typeof ssr !== 'object' ? {} : ssr\n ) as SSROptions;\n tolgeeSSR = useTolgeeSSR(tolgee, language, staticData, Boolean(ssr));\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":["useTolgeeSSR","tolgeeInstance","language","staticData","enabled","noWrappingTolgee","useState","getTolgeeWithDeactivatedWrapper","tolgee","Object","assign","t","args","props","getTranslateProps","noWrap","initialRender","setInitialRender","useEffect","useMemo","setEmitterActive","addStaticData","changeLanguage","isLoaded","missingRecords","getRequiredRecords","map","namespace","filter","key","console","warn","join","DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","TolgeeProvider","options","children","fallback","ssr","run","stop","catch","e","error","finally","setLoading","tolgeeSSR","Boolean","loading","optionsWithDefault","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","wrapTagHandlers","result","entries","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","Fragment","T","useTolgee","events","listeners","on","listener"],"mappings":"2OAgCM,SAAUA,EACdC,EACAC,EACAC,EACAC,GAAU,GAEV,MAAOC,GAAoBC,GAAS,KAClCC,OA/BFC,EA+BkCP,EA7BlCQ,OAAAC,OAAAD,OAAAC,OAAA,G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AK/C,EACX0C,EAAOzE,GAAQ2E,QACgBjE,IAAtBoE,EAAG9F,MAAM8B,WAA0B6D,aAAK,EAALA,EAAOI,QAC7CvE,EAAMwE,aAAaF,EAAI,CAAE,EAAEF,EAAaD,IACxCnE,EAAMwE,aAAaF,EAE1B,MACCL,EAAOzE,GAAO+B,CACf,IAGI0C,CAAM,EAGFG,EACXK,GAEIC,MAAMC,QAAQF,GACTzE,EAAM4E,SAASC,QAAQJ,GAEvBA,ECpCEK,EAAyBtG,IACpC,MAAMgB,EAAOhB,EAA2BuG,SAAWvG,EAAM8B,cAC7CJ,IAARV,GAEFC,QAAQoB,MAAM,oCAEhB,MAAMmE,EACJxG,EAAMwG,eACJxG,EAA2BuG,QAAUvG,EAAM8B,cAAWJ,GAEpD+E,EAAcb,EAClB5F,EAAMF,EAAE,CACNkB,IAAKA,EACLuE,OAAQC,EAAgBxF,EAAMuF,QAC9BiB,eACAtG,OAAQF,EAAME,OACd4D,GAAI9D,EAAM8D,GACVzE,SAAUW,EAAMX,YAIpB,OAAOmC,EAAAqB,cAAArB,EAAAkF,SAAA,KAAGD,EAAe,ECddE,EAAiB3G,IAC5B,MAAMF,EAAEA,GAAM+D,IAEd,OAAOrC,EAAAqB,cAACyD,EAAM1G,OAAAC,OAAA,CAAAC,EAAGA,GAA8BE,GAAS,ECT7C4G,EAAaC,IACxB,MAAMlH,OAAEA,GAAWwD,KAEbO,SAAEA,GAAaH,IASrB,OAPAlD,GAAU,KACR,MAAMyG,EAAYD,eAAAA,EAAQhG,KAAKuB,GAAMzC,EAAOoH,GAAG3E,EAAGsB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQ1F,KAAK,OAEVxB,CAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React, { useState, useEffect, useMemo, Suspense, useContext, useCallback, useRef } from 'react';
|
|
2
|
-
import {
|
|
2
|
+
import { getTranslateProps, getFallback, getFallbackArray } from '@tolgee/web';
|
|
3
3
|
export * from '@tolgee/web';
|
|
4
4
|
|
|
5
5
|
function getTolgeeWithDeactivatedWrapper(tolgee) {
|
|
@@ -15,25 +15,23 @@ function getTolgeeWithDeactivatedWrapper(tolgee) {
|
|
|
15
15
|
*
|
|
16
16
|
* It also ensures that the first render is done without wrapping and so it avoids
|
|
17
17
|
* "client different than server" issues.
|
|
18
|
-
*
|
|
19
|
-
* If no language data and static data are provided no action is taken
|
|
20
|
-
*
|
|
18
|
+
* *
|
|
21
19
|
* @param tolgeeInstance initialized Tolgee instance
|
|
22
20
|
* @param language language that is obtained outside of Tolgee on the server and client
|
|
23
21
|
* @param staticData static data for the language
|
|
22
|
+
* @param enabled if set to false, no action is taken
|
|
24
23
|
*/
|
|
25
|
-
function useTolgeeSSR(tolgeeInstance, language, staticData) {
|
|
26
|
-
const enabled = Boolean(language || staticData);
|
|
24
|
+
function useTolgeeSSR(tolgeeInstance, language, staticData, enabled = true) {
|
|
27
25
|
const [noWrappingTolgee] = useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
|
|
28
26
|
const [initialRender, setInitialRender] = useState(enabled);
|
|
29
27
|
useEffect(() => {
|
|
30
28
|
setInitialRender(false);
|
|
31
29
|
}, []);
|
|
32
30
|
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
31
|
if (enabled) {
|
|
32
|
+
// we have to prepare tolgee before rendering children
|
|
33
|
+
// so translations are available right away
|
|
34
|
+
// events emitting must be off, to not trigger re-render while rendering
|
|
37
35
|
tolgeeInstance.setEmitterActive(false);
|
|
38
36
|
tolgeeInstance.addStaticData(staticData);
|
|
39
37
|
tolgeeInstance.changeLanguage(language);
|
|
@@ -41,18 +39,16 @@ function useTolgeeSSR(tolgeeInstance, language, staticData) {
|
|
|
41
39
|
}
|
|
42
40
|
}, [language, staticData, tolgeeInstance]);
|
|
43
41
|
useState(() => {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
|
|
55
|
-
}
|
|
42
|
+
// running this function only on first render
|
|
43
|
+
if (!tolgeeInstance.isLoaded() && enabled) {
|
|
44
|
+
// warning user, that static data provided are not sufficient
|
|
45
|
+
// for proper SSR render
|
|
46
|
+
const missingRecords = tolgeeInstance
|
|
47
|
+
.getRequiredRecords(language)
|
|
48
|
+
.map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
|
|
49
|
+
.filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
|
|
50
|
+
// eslint-disable-next-line no-console
|
|
51
|
+
console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
|
|
56
52
|
}
|
|
57
53
|
});
|
|
58
54
|
return initialRender ? noWrappingTolgee : tolgeeInstance;
|
|
@@ -69,7 +65,7 @@ const getProviderInstance = () => {
|
|
|
69
65
|
return ProviderInstance;
|
|
70
66
|
};
|
|
71
67
|
let LAST_TOLGEE_INSTANCE = undefined;
|
|
72
|
-
const TolgeeProvider = ({ tolgee, options, children, fallback,
|
|
68
|
+
const TolgeeProvider = ({ tolgee, options, children, fallback, ssr, }) => {
|
|
73
69
|
// prevent restarting tolgee unnecesarly
|
|
74
70
|
// however if the instance change on hot-reloading
|
|
75
71
|
// we want to restart
|
|
@@ -90,7 +86,9 @@ const TolgeeProvider = ({ tolgee, options, children, fallback, staticData, langu
|
|
|
90
86
|
});
|
|
91
87
|
}
|
|
92
88
|
}, [tolgee]);
|
|
93
|
-
|
|
89
|
+
let tolgeeSSR = tolgee;
|
|
90
|
+
const { language, staticData } = (typeof ssr !== 'object' ? {} : ssr);
|
|
91
|
+
tolgeeSSR = useTolgeeSSR(tolgee, language, staticData, Boolean(ssr));
|
|
94
92
|
const [loading, setLoading] = useState(!tolgeeSSR.isLoaded());
|
|
95
93
|
const optionsWithDefault = Object.assign(Object.assign({}, DEFAULT_REACT_OPTIONS), options);
|
|
96
94
|
const TolgeeProviderContext = getProviderInstance();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tolgee-react.esm.mjs","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":[],"mappings":";;;;AAQA,SAAS,+BAA+B,CACtC,MAAsB,EAAA;AAEtB,IAAA,OAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,EAAA,EACK,MAAM,CAAA,EAAA,EACT,CAAC,CAAC,GAAG,IAAI,EAAA;;AAEP,YAAA,MAAM,KAAK,GAAG,iBAAiB,CAAC,GAAG,IAAI,CAAC,CAAC;YACzC,OAAO,MAAM,CAAC,CAAC,CAAM,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,EAAA,EAAA,KAAK,KAAE,MAAM,EAAE,IAAI,EAAA,CAAA,CAAG,CAAC;AAC9C,SAAC,EACD,CAAA,CAAA;AACJ,CAAC;AAED;;;;;;;;;;;;AAYG;SACa,YAAY,CAC1B,cAA8B,EAC9B,QAAiB,EACjB,UAAyC,EAAA;IAEzC,MAAM,OAAO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WAAW,EAAE,CAAC;IAEnC,SAAS,CAAC,MAAK;QACb,MAAM,SAAS,GAAG,MAAM,KAAN,IAAA,IAAA,MAAM,uBAAN,MAAM,CAAE,GAAG,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC7D,QAAA,OAAO,MAAK;AACV,YAAA,SAAS,aAAT,SAAS,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAT,SAAS,CAAE,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;AAC3D,SAAC,CAAC;AACJ,KAAC,EAAE,CAAC,MAAM,KAAA,IAAA,IAAN,MAAM,KAAN,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,MAAM,CAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAExB,IAAA,OAAO,MAAM,CAAC;AAChB;;;;"}
|
|
1
|
+
{"version":3,"file":"tolgee-react.esm.mjs","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} 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 * @param enabled if set to false, no action is taken\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined,\n enabled = true\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 if (enabled) {\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 }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded() && enabled) {\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 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 type SSROptions = {\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 interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * use this option if you use SSR\n *\n * You can pass staticData and language\n * which will be set to tolgee instance for the initial render\n *\n * Don't switch between ssr and non-ssr dynamically\n */\n ssr?: SSROptions | boolean;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n ssr,\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 let tolgeeSSR = tolgee;\n\n const { language, staticData } = (\n typeof ssr !== 'object' ? {} : ssr\n ) as SSROptions;\n tolgeeSSR = useTolgeeSSR(tolgee, language, staticData, Boolean(ssr));\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":[],"mappings":";;;;AAOA,SAAS,+BAA+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 +21,23 @@
|
|
|
21
21
|
*
|
|
22
22
|
* It also ensures that the first render is done without wrapping and so it avoids
|
|
23
23
|
* "client different than server" issues.
|
|
24
|
-
*
|
|
25
|
-
* If no language data and static data are provided no action is taken
|
|
26
|
-
*
|
|
24
|
+
* *
|
|
27
25
|
* @param tolgeeInstance initialized Tolgee instance
|
|
28
26
|
* @param language language that is obtained outside of Tolgee on the server and client
|
|
29
27
|
* @param staticData static data for the language
|
|
28
|
+
* @param enabled if set to false, no action is taken
|
|
30
29
|
*/
|
|
31
|
-
function useTolgeeSSR(tolgeeInstance, language, staticData) {
|
|
32
|
-
const enabled = Boolean(language || staticData);
|
|
30
|
+
function useTolgeeSSR(tolgeeInstance, language, staticData, enabled = true) {
|
|
33
31
|
const [noWrappingTolgee] = React.useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
|
|
34
32
|
const [initialRender, setInitialRender] = React.useState(enabled);
|
|
35
33
|
React.useEffect(() => {
|
|
36
34
|
setInitialRender(false);
|
|
37
35
|
}, []);
|
|
38
36
|
React.useMemo(() => {
|
|
39
|
-
// we have to prepare tolgee before rendering children
|
|
40
|
-
// so translations are available right away
|
|
41
|
-
// events emitting must be off, to not trigger re-render while rendering
|
|
42
37
|
if (enabled) {
|
|
38
|
+
// we have to prepare tolgee before rendering children
|
|
39
|
+
// so translations are available right away
|
|
40
|
+
// events emitting must be off, to not trigger re-render while rendering
|
|
43
41
|
tolgeeInstance.setEmitterActive(false);
|
|
44
42
|
tolgeeInstance.addStaticData(staticData);
|
|
45
43
|
tolgeeInstance.changeLanguage(language);
|
|
@@ -47,18 +45,16 @@
|
|
|
47
45
|
}
|
|
48
46
|
}, [language, staticData, tolgeeInstance]);
|
|
49
47
|
React.useState(() => {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
|
|
61
|
-
}
|
|
48
|
+
// running this function only on first render
|
|
49
|
+
if (!tolgeeInstance.isLoaded() && enabled) {
|
|
50
|
+
// warning user, that static data provided are not sufficient
|
|
51
|
+
// for proper SSR render
|
|
52
|
+
const missingRecords = tolgeeInstance
|
|
53
|
+
.getRequiredRecords(language)
|
|
54
|
+
.map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
|
|
55
|
+
.filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
|
|
56
|
+
// eslint-disable-next-line no-console
|
|
57
|
+
console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
|
|
62
58
|
}
|
|
63
59
|
});
|
|
64
60
|
return initialRender ? noWrappingTolgee : tolgeeInstance;
|
|
@@ -75,7 +71,7 @@
|
|
|
75
71
|
return ProviderInstance;
|
|
76
72
|
};
|
|
77
73
|
let LAST_TOLGEE_INSTANCE = undefined;
|
|
78
|
-
const TolgeeProvider = ({ tolgee, options, children, fallback,
|
|
74
|
+
const TolgeeProvider = ({ tolgee, options, children, fallback, ssr, }) => {
|
|
79
75
|
// prevent restarting tolgee unnecesarly
|
|
80
76
|
// however if the instance change on hot-reloading
|
|
81
77
|
// we want to restart
|
|
@@ -96,7 +92,9 @@
|
|
|
96
92
|
});
|
|
97
93
|
}
|
|
98
94
|
}, [tolgee]);
|
|
99
|
-
|
|
95
|
+
let tolgeeSSR = tolgee;
|
|
96
|
+
const { language, staticData } = (typeof ssr !== 'object' ? {} : ssr);
|
|
97
|
+
tolgeeSSR = useTolgeeSSR(tolgee, language, staticData, Boolean(ssr));
|
|
100
98
|
const [loading, setLoading] = React.useState(!tolgeeSSR.isLoaded());
|
|
101
99
|
const optionsWithDefault = Object.assign(Object.assign({}, DEFAULT_REACT_OPTIONS), options);
|
|
102
100
|
const TolgeeProviderContext = getProviderInstance();
|