@tolgee/react 5.29.4 → 5.29.6-prerelease.1efc495b.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"tolgee-react.esm.js","sources":["../src/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/useTranslate.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts","../src/useTolgeeSSR.ts"],"sourcesContent":["import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n}) => {\n const [loading, setLoading] = useState(!tolgee.isLoaded());\n\n // prevent restarting tolgee unnecesarly\n // however if the instance change on hot-reloading\n // we want to restart\n useEffect(() => {\n if (LAST_TOLGEE_INSTANCE?.run !== tolgee.run) {\n if (LAST_TOLGEE_INSTANCE) {\n LAST_TOLGEE_INSTANCE.stop();\n }\n LAST_TOLGEE_INSTANCE = tolgee;\n tolgee\n .run()\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n })\n .finally(() => {\n setLoading(false);\n });\n }\n }, [tolgee]);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n","import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n"],"names":[],"mappings":";;;;AAIO,MAAM,qBAAqB,GAAiB;AACjD,IAAA,WAAW,EAAE,IAAI;CAClB,CAAC;AAEF,IAAI,gBAA+D,CAAC;AAE7D,MAAM,mBAAmB,GAAG,MAAK;IACtC,IAAI,CAAC,gBAAgB,EAAE;AACrB,QAAA,gBAAgB,GAAG,KAAK,CAAC,aAAa,CACpC,SAAS,CACV,CAAC;AACH,KAAA;AAED,IAAA,OAAO,gBAAgB,CAAC;AAC1B,EAAE;AAEF,IAAI,oBAAoB,GAA+B,SAAS,CAAC;AAS1D,MAAM,cAAc,GAAkC,CAAC,EAC5D,MAAM,EACN,OAAO,EACP,QAAQ,EACR,QAAQ,GACT,KAAI;AACH,IAAA,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;;;;IAK3D,SAAS,CAAC,MAAK;AACb,QAAA,IAAI,CAAA,oBAAoB,KAApB,IAAA,IAAA,oBAAoB,KAApB,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,oBAAoB,CAAE,GAAG,MAAK,MAAM,CAAC,GAAG,EAAE;AAC5C,YAAA,IAAI,oBAAoB,EAAE;gBACxB,oBAAoB,CAAC,IAAI,EAAE,CAAC;AAC7B,aAAA;YACD,oBAAoB,GAAG,MAAM,CAAC;YAC9B,MAAM;AACH,iBAAA,GAAG,EAAE;AACL,iBAAA,KAAK,CAAC,CAAC,CAAC,KAAI;;AAEX,gBAAA,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnB,aAAC,CAAC;iBACD,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CAAC;KACzB,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,CAAC,MAAK;;;;AAIX,QAAA,cAAc,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;AACvC,QAAA,cAAc,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;AACzC,QAAA,cAAc,CAAC,cAAc,CAAC,QAAS,CAAC,CAAC;AACzC,QAAA,cAAc,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;KACvC,EAAE,CAAC,QAAQ,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC;IAE3C,QAAQ,CAAC,MAAK;;AAEZ,QAAA,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,EAAE;;;YAG9B,MAAM,cAAc,GAAG,cAAc;iBAClC,kBAAkB,CAAC,QAAQ,CAAC;iBAC5B,GAAG,CAAC,CAAC,EAAE,SAAS,EAAE,QAAQ,EAAE,KAC3B,SAAS,GAAG,CAAG,EAAA,SAAS,CAAI,CAAA,EAAA,QAAQ,EAAE,GAAG,QAAQ,CAClD;AACA,iBAAA,MAAM,CAAC,CAAC,GAAG,KAAK,EAAC,UAAU,KAAV,IAAA,IAAA,UAAU,uBAAV,UAAU,CAAG,GAAG,CAAC,CAAA,CAAC,CAAC;;YAGvC,OAAO,CAAC,IAAI,CACV,CAAyE,sEAAA,EAAA,cAAc,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK,CAAI,CAAA,EAAA,GAAG,CAAG,CAAA,CAAA,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAE,CAAA,CAC9H,CAAC;AACH,SAAA;AACH,KAAC,CAAC,CAAC;IAEH,OAAO,aAAa,GAAG,gBAAgB,GAAG,cAAc,CAAC;AAC3D;;;;"}
1
+ {"version":3,"file":"tolgee-react.esm.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 * 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 [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import 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 if (ssr) {\n const { language, staticData } = (\n typeof ssr === 'boolean' ? {} : ssr\n ) as SSROptions;\n tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n }\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+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;AAEzC,IAAA,MAAM,CAAC,gBAAgB,CAAC,GAAG,QAAQ,CAAC,MAClC,+BAA+B,CAAC,cAAc,CAAC,CAChD,CAAC;IAEF,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAEzD,SAAS,CAAC,MAAK;QACb,gBAAgB,CAAC,KAAK,CAAC,CAAC;KACzB,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,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A,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,2 +1,2 @@
1
- import e,{useState as n,useEffect as t,Suspense as r,useContext as o,useCallback as s,useRef as i,useMemo as c}from"react";import{getFallback as a,getFallbackArray as l,getTranslateProps as u}from"@tolgee/web";export*from"@tolgee/web";const d={useSuspense:!0};let g;const p=()=>(g||(g=e.createContext(void 0)),g);let b;const m=({tolgee:o,options:s,children:i,fallback:c})=>{const[a,l]=n(!o.isLoaded());t((()=>{(null==b?void 0:b.run)!==o.run&&(b&&b.stop(),b=o,o.run().catch((e=>{console.error(e)})).finally((()=>{l(!1)})))}),[o]);const u=Object.assign(Object.assign({},d),s),g=p();return u.useSuspense?e.createElement(g.Provider,{value:{tolgee:o,options:u}},a?c:e.createElement(r,{fallback:c||null},i)):e.createElement(g.Provider,{value:{tolgee:o,options:u}},a?c:i)};let f;const v=e=>n=>(f={tolgee:n,options:Object.assign(Object.assign({},d),e)},n);const j=()=>{const e=p(),n=o(e)||f;if(!n)throw new Error("Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?");return n},h=()=>{const[e,t]=n(0);return{instance:e,rerender:s((()=>{t((e=>e+1))}),[t])}},E=(e,n)=>{const{tolgee:r,options:o}=j(),c=a(e),u=l(c).join(":"),d=Object.assign(Object.assign({},o),n),{rerender:g,instance:p}=h(),b=i(),m=i([]);m.current=[];const f=r.isLoaded(c);t((()=>{const e=r.onNsUpdate(g);return b.current=e,e.subscribeNs(c),m.current.forEach((n=>{e.subscribeNs(n)})),()=>{e.unsubscribe()}}),[u,r]),t((()=>(r.addActiveNs(c),()=>r.removeActiveNs(c))),[u,r]);const v=s((e=>{var n;const t=null!==(n=e.ns)&&void 0!==n?n:null==c?void 0:c[0];return(e=>{var n;m.current.push(e),null===(n=b.current)||void 0===n||n.subscribeNs(e)})(t),r.t(Object.assign(Object.assign({},e),{ns:t}))}),[r,p]);if(d.useSuspense&&!f)throw r.addActiveNs(c,!0);return{t:v,isLoading:!f}},O=(e,n)=>{const{t:t,isLoading:r}=E(e,n);return{t:s(((...e)=>{const n=u(...e);return t(n)}),[t]),isLoading:r}},y=n=>{if(!n)return;const t={};return Object.entries(n||{}).forEach((([n,r])=>{if("function"==typeof r)t[n]=e=>r(N(e));else if(e.isValidElement(r)){const o=r;t[n]=n=>void 0===o.props.children&&(null==n?void 0:n.length)?e.cloneElement(o,{},N(n)):e.cloneElement(o)}else t[n]=r})),t},N=n=>Array.isArray(n)?e.Children.toArray(n):n,A=n=>{const t=n.keyName||n.children;void 0===t&&console.error("T component: keyName not defined");const r=n.defaultValue||(n.keyName?n.children:void 0),o=N(n.t({key:t,params:y(n.params),defaultValue:r,noWrap:n.noWrap,ns:n.ns,language:n.language}));return e.createElement(e.Fragment,null,o)},L=n=>{const{t:t}=E();return e.createElement(A,Object.assign({t:t},n))},k=e=>{const{tolgee:n}=j(),{rerender:r}=h();return t((()=>{const t=null==e?void 0:e.map((e=>n.on(e,r)));return()=>{null==t||t.forEach((e=>e.unsubscribe()))}}),[null==e?void 0:e.join(":")]),n};function w(e,r,o){const[s]=n((()=>{return n=e,Object.assign(Object.assign({},n),{t(...e){const t=u(...e);return n.t(Object.assign(Object.assign({},t),{noWrap:!0}))}});var n})),[i,a]=n(!0);return t((()=>{a(!1)}),[]),c((()=>{e.setEmitterActive(!1),e.addStaticData(o),e.changeLanguage(r),e.setEmitterActive(!0)}),[r,o,e]),n((()=>{if(!e.isLoaded()){const n=e.getRequiredRecords(r).map((({namespace:e,language:n})=>e?`${e}:${n}`:n)).filter((e=>!(null==o?void 0:o[e])));console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${n.map((e=>`"${e}"`)).join(", ")}`)}})),i?s:e}export{v as GlobalContextPlugin,L as T,A as TBase,m as TolgeeProvider,p as getProviderInstance,k as useTolgee,w as useTolgeeSSR,O as useTranslate};
1
+ import e,{useState as t,useEffect as n,useMemo as r,Suspense as o,useContext as s,useCallback as a,useRef as i}from"react";import{getTranslateProps as c,getFallback as l,getFallbackArray as u}from"@tolgee/web";export*from"@tolgee/web";function d(e,o,s){const[a]=t((()=>{return t=e,Object.assign(Object.assign({},t),{t(...e){const n=c(...e);return t.t(Object.assign(Object.assign({},n),{noWrap:!0}))}});var t})),[i,l]=t(!0);return n((()=>{l(!1)}),[]),r((()=>{e.setEmitterActive(!1),e.addStaticData(s),e.changeLanguage(o),e.setEmitterActive(!0)}),[o,s,e]),t((()=>{if(!e.isLoaded()){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(", ")}`)}})),i?a: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:i,ssr:c})=>{n((()=>{(null==f?void 0:f.run)!==r.run&&(f&&f.stop(),f=r,r.run().catch((e=>{console.error(e)})).finally((()=>{p(!1)})))}),[r]);let l=r;if(c){const{language:e,staticData:t}="boolean"==typeof c?{}:c;l=d(r,e,t)}const[u,p]=t(!l.isLoaded()),m=Object.assign(Object.assign({},g),s),v=b();return m.useSuspense?e.createElement(v.Provider,{value:{tolgee:l,options:m}},u?i:e.createElement(o,{fallback:i||null},a)):e.createElement(v.Provider,{value:{tolgee:l,options:m}},u?i: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),c=u(s).join(":"),d=Object.assign(Object.assign({},o),t),{rerender:g,instance:p}=E(),b=i(),f=i([]);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()}}),[c,r]),n((()=>(r.addActiveNs(s),()=>r.removeActiveNs(s))),[c,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=c(...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.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tolgee-react.esm.min.js","sources":["../src/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/useTranslate.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts","../src/useTolgeeSSR.ts"],"sourcesContent":["import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n}) => {\n const [loading, setLoading] = useState(!tolgee.isLoaded());\n\n // prevent restarting tolgee unnecesarly\n // however if the instance change on hot-reloading\n // we want to restart\n useEffect(() => {\n if (LAST_TOLGEE_INSTANCE?.run !== tolgee.run) {\n if (LAST_TOLGEE_INSTANCE) {\n LAST_TOLGEE_INSTANCE.stop();\n }\n LAST_TOLGEE_INSTANCE = tolgee;\n tolgee\n .run()\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n })\n .finally(() => {\n setLoading(false);\n });\n }\n }, [tolgee]);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n","import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n"],"names":["DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","TolgeeProvider","tolgee","options","children","fallback","loading","setLoading","useState","isLoaded","useEffect","run","stop","catch","e","console","error","finally","optionsWithDefault","Object","assign","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","join","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","t","props","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","getTranslateProps","wrapTagHandlers","result","entries","key","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","noWrap","language","Fragment","T","useTolgee","events","listeners","map","on","listener","useTolgeeSSR","tolgeeInstance","staticData","noWrappingTolgee","getTolgeeWithDeactivatedWrapper","args","initialRender","setInitialRender","useMemo","setEmitterActive","addStaticData","changeLanguage","missingRecords","getRequiredRecords","namespace","filter","warn"],"mappings":"2OAIO,MAAMA,EAAsC,CACjDC,aAAa,GAGf,IAAIC,EAEG,MAAMC,EAAsB,KAC5BD,IACHA,EAAmBE,EAAMC,mBACvBC,IAIGJ,GAGT,IAAIK,EASG,MAAMC,EAAgD,EAC3DC,SACAC,UACAC,WACAC,eAEA,MAAOC,EAASC,GAAcC,GAAUN,EAAOO,Y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W,GAEA,MAAOC,GAAoB7F,GAAS,KAClC8F,OA7BFpG,EA6BkCiG,EA3BlChF,OAAAC,OAAAD,OAAAC,OAAA,GACKlB,GAAM,CACT,CAAAwD,IAAK6C,GAEH,MAAM5C,EAAQS,KAAqBmC,GACnC,OAAOrG,EAAOwD,EAAOvC,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAuC,IAAO6B,QAAQ,IACrC,IATL,IACEtF,CA6BiD,KAG1CsG,EAAeC,GAAoBjG,GAAS,GAmCnD,OAjCAE,GAAU,KACR+F,GAAiB,EAAM,GACtB,IAEHC,GAAQ,KAINP,EAAeQ,kBAAiB,GAChCR,EAAeS,cAAcR,GAC7BD,EAAeU,eAAepB,GAC9BU,EAAeQ,kBAAiB,EAAK,GACpC,CAAClB,EAAUW,EAAYD,IAE1B3F,GAAS,KAEP,IAAK2F,EAAe1F,WAAY,CAG9B,MAAMqG,EAAiBX,EACpBY,mBAAmBtB,GACnBM,KAAI,EAAGiB,YAAWvB,cACjBuB,EAAY,GAAGA,KAAavB,IAAaA,IAE1CwB,QAAQzC,KAAS4B,eAAAA,EAAa5B,MAGjCzD,QAAQmG,KACN,yEAAyEJ,EAAef,KAAKvB,GAAQ,IAAIA,OAAQ3B,KAAK,QAEzH,KAGI2D,EAAgBH,EAAmBF,CAC5C"}
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 * 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 [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import 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 if (ssr) {\n const { language, staticData } = (\n typeof ssr === 'boolean' ? {} : ssr\n ) as SSROptions;\n tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n }\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","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","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":"oPAiCgBA,EACdC,EACAC,EACAC,GAEA,MAAOC,GAAoBC,GAAS,KAClCC,OA/BFC,EA+BkCN,EA7BlCO,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+BiD,KAG1CQ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CL,EAAOxE,GAAO8B,CACf,IAGI0C,CAAM,EAGFG,EACXK,GAEIC,MAAMC,QAAQF,GACTxE,EAAM2E,SAASC,QAAQJ,GAEvBA,ECpCEK,EAAyBrG,IACpC,MAAMgB,EAAOhB,EAA2BsG,SAAWtG,EAAM8B,cAC7CJ,IAARV,GAEFC,QAAQoB,MAAM,oCAEhB,MAAMkE,EACJvG,EAAMuG,eACJvG,EAA2BsG,QAAUtG,EAAM8B,cAAWJ,GAEpD8E,EAAcb,EAClB3F,EAAMF,EAAE,CACNkB,IAAKA,EACLsE,OAAQC,EAAgBvF,EAAMsF,QAC9BiB,eACArG,OAAQF,EAAME,OACd2D,GAAI7D,EAAM6D,GACVvE,SAAUU,EAAMV,YAIpB,OAAOkC,EAAAoB,cAAApB,EAAAiF,SAAA,KAAGD,EAAe,ECddE,EAAiB1G,IAC5B,MAAMF,EAAEA,GAAM8D,IAEd,OAAOpC,EAAAoB,cAACyD,EAAMzG,OAAAC,OAAA,CAAAC,EAAGA,GAA8BE,GAAS,ECT7C2G,EAAaC,IACxB,MAAMjH,OAAEA,GAAWuD,KAEbO,SAAEA,GAAaH,IASrB,OAPAjD,GAAU,KACR,MAAMwG,EAAYD,eAAAA,EAAQ/F,KAAKuB,GAAMzC,EAAOmH,GAAG1E,EAAGqB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQzF,KAAK,OAEVxB,CAAM"}
@@ -1,2 +1,2 @@
1
- import e,{useState as n,useEffect as t,Suspense as r,useContext as o,useCallback as s,useRef as i,useMemo as c}from"react";import{getFallback as a,getFallbackArray as l,getTranslateProps as u}from"@tolgee/web";export*from"@tolgee/web";const d={useSuspense:!0};let g;const p=()=>(g||(g=e.createContext(void 0)),g);let b;const m=({tolgee:o,options:s,children:i,fallback:c})=>{const[a,l]=n(!o.isLoaded());t((()=>{(null==b?void 0:b.run)!==o.run&&(b&&b.stop(),b=o,o.run().catch((e=>{console.error(e)})).finally((()=>{l(!1)})))}),[o]);const u=Object.assign(Object.assign({},d),s),g=p();return u.useSuspense?e.createElement(g.Provider,{value:{tolgee:o,options:u}},a?c:e.createElement(r,{fallback:c||null},i)):e.createElement(g.Provider,{value:{tolgee:o,options:u}},a?c:i)};let f;const v=e=>n=>(f={tolgee:n,options:Object.assign(Object.assign({},d),e)},n);const j=()=>{const e=p(),n=o(e)||f;if(!n)throw new Error("Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?");return n},h=()=>{const[e,t]=n(0);return{instance:e,rerender:s((()=>{t((e=>e+1))}),[t])}},E=(e,n)=>{const{tolgee:r,options:o}=j(),c=a(e),u=l(c).join(":"),d=Object.assign(Object.assign({},o),n),{rerender:g,instance:p}=h(),b=i(),m=i([]);m.current=[];const f=r.isLoaded(c);t((()=>{const e=r.onNsUpdate(g);return b.current=e,e.subscribeNs(c),m.current.forEach((n=>{e.subscribeNs(n)})),()=>{e.unsubscribe()}}),[u,r]),t((()=>(r.addActiveNs(c),()=>r.removeActiveNs(c))),[u,r]);const v=s((e=>{var n;const t=null!==(n=e.ns)&&void 0!==n?n:null==c?void 0:c[0];return(e=>{var n;m.current.push(e),null===(n=b.current)||void 0===n||n.subscribeNs(e)})(t),r.t(Object.assign(Object.assign({},e),{ns:t}))}),[r,p]);if(d.useSuspense&&!f)throw r.addActiveNs(c,!0);return{t:v,isLoading:!f}},O=(e,n)=>{const{t:t,isLoading:r}=E(e,n);return{t:s(((...e)=>{const n=u(...e);return t(n)}),[t]),isLoading:r}},y=n=>{if(!n)return;const t={};return Object.entries(n||{}).forEach((([n,r])=>{if("function"==typeof r)t[n]=e=>r(N(e));else if(e.isValidElement(r)){const o=r;t[n]=n=>void 0===o.props.children&&(null==n?void 0:n.length)?e.cloneElement(o,{},N(n)):e.cloneElement(o)}else t[n]=r})),t},N=n=>Array.isArray(n)?e.Children.toArray(n):n,A=n=>{const t=n.keyName||n.children;void 0===t&&console.error("T component: keyName not defined");const r=n.defaultValue||(n.keyName?n.children:void 0),o=N(n.t({key:t,params:y(n.params),defaultValue:r,noWrap:n.noWrap,ns:n.ns,language:n.language}));return e.createElement(e.Fragment,null,o)},L=n=>{const{t:t}=E();return e.createElement(A,Object.assign({t:t},n))},k=e=>{const{tolgee:n}=j(),{rerender:r}=h();return t((()=>{const t=null==e?void 0:e.map((e=>n.on(e,r)));return()=>{null==t||t.forEach((e=>e.unsubscribe()))}}),[null==e?void 0:e.join(":")]),n};function w(e,r,o){const[s]=n((()=>{return n=e,Object.assign(Object.assign({},n),{t(...e){const t=u(...e);return n.t(Object.assign(Object.assign({},t),{noWrap:!0}))}});var n})),[i,a]=n(!0);return t((()=>{a(!1)}),[]),c((()=>{e.setEmitterActive(!1),e.addStaticData(o),e.changeLanguage(r),e.setEmitterActive(!0)}),[r,o,e]),n((()=>{if(!e.isLoaded()){const n=e.getRequiredRecords(r).map((({namespace:e,language:n})=>e?`${e}:${n}`:n)).filter((e=>!(null==o?void 0:o[e])));console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${n.map((e=>`"${e}"`)).join(", ")}`)}})),i?s:e}export{v as GlobalContextPlugin,L as T,A as TBase,m as TolgeeProvider,p as getProviderInstance,k as useTolgee,w as useTolgeeSSR,O as useTranslate};
1
+ import e,{useState as t,useEffect as n,useMemo as r,Suspense as o,useContext as s,useCallback as a,useRef as i}from"react";import{getTranslateProps as c,getFallback as l,getFallbackArray as u}from"@tolgee/web";export*from"@tolgee/web";function d(e,o,s){const[a]=t((()=>{return t=e,Object.assign(Object.assign({},t),{t(...e){const n=c(...e);return t.t(Object.assign(Object.assign({},n),{noWrap:!0}))}});var t})),[i,l]=t(!0);return n((()=>{l(!1)}),[]),r((()=>{e.setEmitterActive(!1),e.addStaticData(s),e.changeLanguage(o),e.setEmitterActive(!0)}),[o,s,e]),t((()=>{if(!e.isLoaded()){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(", ")}`)}})),i?a: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:i,ssr:c})=>{n((()=>{(null==f?void 0:f.run)!==r.run&&(f&&f.stop(),f=r,r.run().catch((e=>{console.error(e)})).finally((()=>{p(!1)})))}),[r]);let l=r;if(c){const{language:e,staticData:t}="boolean"==typeof c?{}:c;l=d(r,e,t)}const[u,p]=t(!l.isLoaded()),m=Object.assign(Object.assign({},g),s),v=b();return m.useSuspense?e.createElement(v.Provider,{value:{tolgee:l,options:m}},u?i:e.createElement(o,{fallback:i||null},a)):e.createElement(v.Provider,{value:{tolgee:l,options:m}},u?i: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),c=u(s).join(":"),d=Object.assign(Object.assign({},o),t),{rerender:g,instance:p}=E(),b=i(),f=i([]);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()}}),[c,r]),n((()=>(r.addActiveNs(s),()=>r.removeActiveNs(s))),[c,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=c(...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/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/useTranslate.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts","../src/useTolgeeSSR.ts"],"sourcesContent":["import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n}) => {\n const [loading, setLoading] = useState(!tolgee.isLoaded());\n\n // prevent restarting tolgee unnecesarly\n // however if the instance change on hot-reloading\n // we want to restart\n useEffect(() => {\n if (LAST_TOLGEE_INSTANCE?.run !== tolgee.run) {\n if (LAST_TOLGEE_INSTANCE) {\n LAST_TOLGEE_INSTANCE.stop();\n }\n LAST_TOLGEE_INSTANCE = tolgee;\n tolgee\n .run()\n .catch((e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n })\n .finally(() => {\n setLoading(false);\n });\n }\n }, [tolgee]);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n","import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n"],"names":["DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","TolgeeProvider","tolgee","options","children","fallback","loading","setLoading","useState","isLoaded","useEffect","run","stop","catch","e","console","error","finally","optionsWithDefault","Object","assign","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","join","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","t","props","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","getTranslateProps","wrapTagHandlers","result","entries","key","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","noWrap","language","Fragment","T","useTolgee","events","listeners","map","on","listener","useTolgeeSSR","tolgeeInstance","staticData","noWrappingTolgee","getTolgeeWithDeactivatedWrapper","args","initialRender","setInitialRender","useMemo","setEmitterActive","addStaticData","changeLanguage","missingRecords","getRequiredRecords","namespace","filter","warn"],"mappings":"2OAIO,MAAMA,EAAsC,CACjDC,aAAa,GAGf,IAAIC,EAEG,MAAMC,EAAsB,KAC5BD,IACHA,EAAmBE,EAAMC,mBACvBC,IAIGJ,GAGT,IAAIK,EASG,MAAMC,EAAgD,EAC3DC,SACAC,UACAC,WACAC,eAEA,MAAOC,EAASC,GAAcC,GAAUN,EAAOO,YAK/CC,GAAU,MACJV,aAAA,EAAAA,EAAsBW,OAAQT,EAAOS,MACnCX,GACFA,EAAqBY,OAEvBZ,EAAuBE,EACvBA,EACGS,MACAE,OAAOC,IAENC,QAAQC,MAAMF,EAAE,IAEjBG,SAAQ,KACPV,GAAW,EAAM,IAEtB,GACA,CAACL,IAEJ,MAAMgB,EAA0BC,OAAAC,OAAAD,OAAAC,OAAA,GAAA3B,GAA0BU,GAEpDkB,EAAwBzB,IAE9B,OAAIsB,EAAmBxB,YAEnBG,EAACyB,cAAAD,EAAsBE,SAAQ,CAC7BC,MAAO,CAAEtB,SAAQC,QAASe,IAEzBZ,EACC,EAEAT,EAAAyB,cAACG,EAAS,CAAApB,SAAUA,GAAY,MAAOD,IAO7CP,EAACyB,cAAAD,EAAsBE,SACrB,CAAAC,MAAO,CAAEtB,SAAQC,QAASe,IAEzBZ,EAAUD,EAAWD,EAExB,EC9EJ,IAAIsB,EAEG,MAAMC,EACVxB,GACAD,IACCwB,EAAgB,CACdx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BuB,EAAY,GAAGA,KAAavB,IAAaA,IAE1CwB,QAAQzC,KAAS4B,eAAAA,EAAa5B,MAGjCzD,QAAQmG,KACN,yEAAyEJ,EAAef,KAAKvB,GAAQ,IAAIA,OAAQ3B,KAAK,QAEzH,KAGI2D,EAAgBH,EAAmBF,CAC5C"}
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 * 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 [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(true);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import 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 if (ssr) {\n const { language, staticData } = (\n typeof ssr === 'boolean' ? {} : ssr\n ) as SSROptions;\n tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n }\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","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","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":"oPAiCgBA,EACdC,EACAC,EACAC,GAEA,MAAOC,GAAoBC,GAAS,KAClCC,OA/BFC,EA+BkCN,EA7BlCO,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+BiD,KAG1CQ,EAAeC,GAAoBX,GAAS,GAmCnD,OAjCAY,GAAU,KACRD,GAAiB,EAAM,GACtB,IAEHE,GAAQ,KAINjB,EAAekB,kBAAiB,GAChClB,EAAemB,cAAcjB,GAC7BF,EAAeoB,eAAenB,GAC9BD,EAAekB,kBAAiB,EAAK,GACpC,CAACjB,EAAUC,EAAYF,IAE1BI,GAAS,KAEP,IAAKJ,EAAeqB,WAAY,CAG9B,MAAMC,EAAiBtB,EACpBuB,mBAAmBtB,GACnBuB,KAAI,EAAGC,YAAWxB,cACjBwB,EAAY,GAAGA,KAAaxB,IAAaA,IAE1CyB,QAAQC,KAASzB,eAAAA,EAAayB,MAGjCC,QAAQC,KACN,yEAAyEP,EAAeE,KAAKG,GAAQ,IAAIA,OAAQG,KAAK,QAEzH,KAGIhB,EAAgBX,EAAmBH,CAC5C,CCzEO,MAAM+B,EAAsC,CACjDC,aAAa,GAGf,IAAIC,EAEG,MAAMC,EAAsB,KAC5BD,IACHA,EAAmBE,EAAMC,m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GA,GAA8BE,GAAS,ECT7C2G,EAAaC,IACxB,MAAMjH,OAAEA,GAAWuD,KAEbO,SAAEA,GAAaH,IASrB,OAPAjD,GAAU,KACR,MAAMwG,EAAYD,eAAAA,EAAQ/F,KAAKuB,GAAMzC,EAAOmH,GAAG1E,EAAGqB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQzF,KAAK,OAEVxB,CAAM"}
@@ -1,7 +1,58 @@
1
- import React, { useState, useEffect, Suspense, useContext, useCallback, useRef, useMemo } from 'react';
2
- import { getFallback, getFallbackArray, getTranslateProps } from '@tolgee/web';
1
+ import React, { useState, useEffect, useMemo, Suspense, useContext, useCallback, useRef } from 'react';
2
+ import { getTranslateProps, getFallback, getFallbackArray } from '@tolgee/web';
3
3
  export * from '@tolgee/web';
4
4
 
5
+ function getTolgeeWithDeactivatedWrapper(tolgee) {
6
+ return Object.assign(Object.assign({}, tolgee), { t(...args) {
7
+ // @ts-ignore
8
+ const props = getTranslateProps(...args);
9
+ return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
10
+ } });
11
+ }
12
+ /**
13
+ * Updates tolgee static data and language, to be ready right away for the first render
14
+ * and therefore compatible with SSR.
15
+ *
16
+ * It also ensures that the first render is done without wrapping and so it avoids
17
+ * "client different than server" issues.
18
+ *
19
+ * If no language data and static data are provided no action is taken
20
+ *
21
+ * @param tolgeeInstance initialized Tolgee instance
22
+ * @param language language that is obtained outside of Tolgee on the server and client
23
+ * @param staticData static data for the language
24
+ */
25
+ function useTolgeeSSR(tolgeeInstance, language, staticData) {
26
+ const [noWrappingTolgee] = useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
27
+ const [initialRender, setInitialRender] = useState(true);
28
+ useEffect(() => {
29
+ setInitialRender(false);
30
+ }, []);
31
+ useMemo(() => {
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
35
+ tolgeeInstance.setEmitterActive(false);
36
+ tolgeeInstance.addStaticData(staticData);
37
+ tolgeeInstance.changeLanguage(language);
38
+ tolgeeInstance.setEmitterActive(true);
39
+ }, [language, staticData, tolgeeInstance]);
40
+ useState(() => {
41
+ // running this function only on first render
42
+ if (!tolgeeInstance.isLoaded()) {
43
+ // warning user, that static data provided are not sufficient
44
+ // for proper SSR render
45
+ const missingRecords = tolgeeInstance
46
+ .getRequiredRecords(language)
47
+ .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
48
+ .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
49
+ // eslint-disable-next-line no-console
50
+ console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
51
+ }
52
+ });
53
+ return initialRender ? noWrappingTolgee : tolgeeInstance;
54
+ }
55
+
5
56
  const DEFAULT_REACT_OPTIONS = {
6
57
  useSuspense: true,
7
58
  };
@@ -13,8 +64,7 @@ const getProviderInstance = () => {
13
64
  return ProviderInstance;
14
65
  };
15
66
  let LAST_TOLGEE_INSTANCE = undefined;
16
- const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
17
- const [loading, setLoading] = useState(!tolgee.isLoaded());
67
+ const TolgeeProvider = ({ tolgee, options, children, fallback, ssr, }) => {
18
68
  // prevent restarting tolgee unnecesarly
19
69
  // however if the instance change on hot-reloading
20
70
  // we want to restart
@@ -35,12 +85,18 @@ const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
35
85
  });
36
86
  }
37
87
  }, [tolgee]);
88
+ let tolgeeSSR = tolgee;
89
+ if (ssr) {
90
+ const { language, staticData } = (typeof ssr === 'boolean' ? {} : ssr);
91
+ tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);
92
+ }
93
+ const [loading, setLoading] = useState(!tolgeeSSR.isLoaded());
38
94
  const optionsWithDefault = Object.assign(Object.assign({}, DEFAULT_REACT_OPTIONS), options);
39
95
  const TolgeeProviderContext = getProviderInstance();
40
96
  if (optionsWithDefault.useSuspense) {
41
- return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? (fallback) : (React.createElement(Suspense, { fallback: fallback || null }, children))));
97
+ return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? (fallback) : (React.createElement(Suspense, { fallback: fallback || null }, children))));
42
98
  }
43
- return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? fallback : children));
99
+ return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? fallback : children));
44
100
  };
45
101
 
46
102
  let globalContext;
@@ -195,54 +251,5 @@ const useTolgee = (events) => {
195
251
  return tolgee;
196
252
  };
197
253
 
198
- function getTolgeeWithDeactivatedWrapper(tolgee) {
199
- return Object.assign(Object.assign({}, tolgee), { t(...args) {
200
- // @ts-ignore
201
- const props = getTranslateProps(...args);
202
- return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
203
- } });
204
- }
205
- /**
206
- * Updates tolgee static data and language, to be ready right away for the first render
207
- * and therefore compatible with SSR.
208
- *
209
- * It also ensures that the first render is done without wrapping and so it avoids
210
- * "client different than server" issues.
211
- *
212
- * @param tolgeeInstance initialized Tolgee instance
213
- * @param language language that is obtained outside of Tolgee on the server and client
214
- * @param staticData static data for the language
215
- */
216
- function useTolgeeSSR(tolgeeInstance, language, staticData) {
217
- const [noWrappingTolgee] = useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
218
- const [initialRender, setInitialRender] = useState(true);
219
- useEffect(() => {
220
- setInitialRender(false);
221
- }, []);
222
- useMemo(() => {
223
- // we have to prepare tolgee before rendering children
224
- // so translations are available right away
225
- // events emitting must be off, to not trigger re-render while rendering
226
- tolgeeInstance.setEmitterActive(false);
227
- tolgeeInstance.addStaticData(staticData);
228
- tolgeeInstance.changeLanguage(language);
229
- tolgeeInstance.setEmitterActive(true);
230
- }, [language, staticData, tolgeeInstance]);
231
- useState(() => {
232
- // running this function only on first render
233
- if (!tolgeeInstance.isLoaded()) {
234
- // warning user, that static data provided are not sufficient
235
- // for proper SSR render
236
- const missingRecords = tolgeeInstance
237
- .getRequiredRecords(language)
238
- .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
239
- .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
240
- // eslint-disable-next-line no-console
241
- console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
242
- }
243
- });
244
- return initialRender ? noWrappingTolgee : tolgeeInstance;
245
- }
246
-
247
254
  export { GlobalContextPlugin, T, TBase, TolgeeProvider, getProviderInstance, useTolgee, useTolgeeSSR, useTranslate };
248
255
  //# sourceMappingURL=tolgee-react.esm.mjs.map