@tolgee/react 5.29.4 → 5.29.6-prerelease.4e3062df.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 isSSR,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * If no language data and static data are provided no action is taken\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const enabled = Boolean(language || staticData);\n\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(enabled);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n if (enabled) {\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n if (enabled && isSSR()) {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance, TolgeeStaticData } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\nimport { useTolgeeSSR } from './useTolgeeSSR';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * Hard set language to this value, use together with `staticData`\n */\n language?: string;\n /**\n * If provided, static data will be hard set to Tolgee cache for initial render\n */\n staticData?: TolgeeStaticData;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n staticData,\n language,\n}) => {\n 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 tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n"],"names":[],"mappings":";;;;AAQA,SAAS,+BAA+B,CACtC,MAAsB,EAAA;AAEtB,IAAA,OAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,EAAA,EACK,MAAM,CAAA,EAAA,EACT,CAAC,CAAC,GAAG,IAAI,EAAA;;AAEP,YAAA,MAAM,KAAK,GAAG,iBAAiB,CAAC,GAAG,IAAI,CAAC,CAAC;YACzC,OAAO,MAAM,CAAC,CAAC,CAAM,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,MAAA,CAAA,EAAA,EAAA,KAAK,KAAE,MAAM,EAAE,IAAI,EAAA,CAAA,CAAG,CAAC;AAC9C,SAAC,EACD,CAAA,CAAA;AACJ,CAAC;AAED;;;;;;;;;;;;AAYG;SACa,YAAY,CAC1B,cAA8B,EAC9B,QAAiB,EACjB,UAAyC,EAAA;IAEzC,MAAM,OAAO,GAAG,OAAO,CAAC,QAAQ,IAAI,UAAU,CAAC,CAAC;AAEhD,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,OAAO,CAAC,CAAC;IAE5D,SAAS,CAAC,MAAK;QACb,gBAAgB,CAAC,KAAK,CAAC,CAAC;KACzB,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,CAAC,MAAK;;;;AAIX,QAAA,IAAI,OAAO,EAAE;AACX,YAAA,cAAc,CAAC,gBAAgB,CAAC,KAA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AAM,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 n,useEffect as t,useMemo as r,Suspense as o,useContext as s,useCallback as a,useRef as i}from"react";import{isSSR as c,getTranslateProps as l,getFallback as u,getFallbackArray as d}from"@tolgee/web";export*from"@tolgee/web";function g(e,o,s){const a=Boolean(o||s),[i]=n((()=>{return n=e,Object.assign(Object.assign({},n),{t(...e){const t=l(...e);return n.t(Object.assign(Object.assign({},t),{noWrap:!0}))}});var n})),[u,d]=n(a);return t((()=>{d(!1)}),[]),r((()=>{a&&(e.setEmitterActive(!1),e.addStaticData(s),e.changeLanguage(o),e.setEmitterActive(!0))}),[o,s,e]),n((()=>{if(a&&c()&&!e.isLoaded()){const n=e.getRequiredRecords(o).map((({namespace:e,language:n})=>e?`${e}:${n}`:n)).filter((e=>!(null==s?void 0:s[e])));console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${n.map((e=>`"${e}"`)).join(", ")}`)}})),u?i:e}const p={useSuspense:!0};let b;const m=()=>(b||(b=e.createContext(void 0)),b);let f;const v=({tolgee:r,options:s,children:a,fallback:i,staticData:c,language:l})=>{const[u,d]=n(!r.isLoaded());t((()=>{(null==f?void 0:f.run)!==r.run&&(f&&f.stop(),f=r,r.run().catch((e=>{console.error(e)})).finally((()=>{d(!1)})))}),[r]);const b=g(r,l,c),v=Object.assign(Object.assign({},p),s),j=m();return v.useSuspense?e.createElement(j.Provider,{value:{tolgee:b,options:v}},u?i:e.createElement(o,{fallback:i||null},a)):e.createElement(j.Provider,{value:{tolgee:b,options:v}},u?i:a)};let j;const h=e=>n=>(j={tolgee:n,options:Object.assign(Object.assign({},p),e)},n);const E=()=>{const e=m(),n=s(e)||j;if(!n)throw new Error("Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?");return n},O=()=>{const[e,t]=n(0);return{instance:e,rerender:a((()=>{t((e=>e+1))}),[t])}},y=(e,n)=>{const{tolgee:r,options:o}=E(),s=u(e),c=d(s).join(":"),l=Object.assign(Object.assign({},o),n),{rerender:g,instance:p}=O(),b=i(),m=i([]);m.current=[];const f=r.isLoaded(s);t((()=>{const e=r.onNsUpdate(g);return b.current=e,e.subscribeNs(s),m.current.forEach((n=>{e.subscribeNs(n)})),()=>{e.unsubscribe()}}),[c,r]),t((()=>(r.addActiveNs(s),()=>r.removeActiveNs(s))),[c,r]);const v=a((e=>{var n;const t=null!==(n=e.ns)&&void 0!==n?n:null==s?void 0:s[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(l.useSuspense&&!f)throw r.addActiveNs(s,!0);return{t:v,isLoading:!f}},N=(e,n)=>{const{t:t,isLoading:r}=y(e,n);return{t:a(((...e)=>{const n=l(...e);return t(n)}),[t]),isLoading:r}},A=n=>{if(!n)return;const t={};return Object.entries(n||{}).forEach((([n,r])=>{if("function"==typeof r)t[n]=e=>r(L(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,{},L(n)):e.cloneElement(o)}else t[n]=r})),t},L=n=>Array.isArray(n)?e.Children.toArray(n):n,k=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=L(n.t({key:t,params:A(n.params),defaultValue:r,noWrap:n.noWrap,ns:n.ns,language:n.language}));return e.createElement(e.Fragment,null,o)},w=n=>{const{t:t}=y();return e.createElement(k,Object.assign({t:t},n))},S=e=>{const{tolgee:n}=E(),{rerender:r}=O();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};export{h as GlobalContextPlugin,w as T,k as TBase,v as TolgeeProvider,m as getProviderInstance,S as useTolgee,g as useTolgeeSSR,N 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,YAK/CC,GAAU,MACJV,aAAA,EAAAA,EAAsBW,OAAQT,EAAOS,MACnCX,GACFA,EAAqBY,OAEvBZ,EAAuBE,EACvBA,EACGS,MACAE,OAAOC,IAENC,QAAQC,MAAMF,EAAE,IAEjBG,SAAQ,K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ACnC,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 isSSR,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * If no language data and static data are provided no action is taken\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const enabled = Boolean(language || staticData);\n\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(enabled);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n if (enabled) {\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n if (enabled && isSSR()) {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance, TolgeeStaticData } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\nimport { useTolgeeSSR } from './useTolgeeSSR';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * Hard set language to this value, use together with `staticData`\n */\n language?: string;\n /**\n * If provided, static data will be hard set to Tolgee cache for initial render\n */\n staticData?: TolgeeStaticData;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n staticData,\n language,\n}) => {\n 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 tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n"],"names":["useTolgeeSSR","tolgeeInstance","language","staticData","enabled","Boolean","noWrappingTolgee","useState","getTolgeeWithDeactivatedWrapper","tolgee","Object","assign","t","args","props","getTranslateProps","noWrap","initialRender","setInitialRender","useEffect","useMemo","setEmitterActive","addStaticData","changeLanguage","isSSR","isLoaded","missingRecords","getRequiredRecords","map","namespace","filter","key","console","warn","join","DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","TolgeeProvider","options","children","fallback","loading","setLoading","run","stop","catch","e","error","finally","tolgeeSSR","optionsWithDefault","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","wrapTagHandlers","result","entries","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","Fragment","T","useTolgee","events","listeners","on","listener"],"mappings":"+PAkCgBA,EACdC,EACAC,EACAC,GAEA,MAAMC,EAAUC,QAAQH,GAAYC,IAE7BG,GAAoBC,GAAS,KAClCC,OAjCFC,EAiCkCR,EA/BlCS,OAAAC,OAAAD,OAAAC,OAAA,GACKF,GAAM,CACT,CAAAG,IAAKC,GAEH,MAAMC,EAAQC,KAAqBF,GACnC,OAAOJ,EAAOG,EAAOF,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAG,IAAOE,QAAQ,IACrC,IATL,IACEP,CAiCiD,KAG1CQ,EAAeC,GAAoBX,EAASH,GAuCnD,OArCAe,GAAU,KACRD,GAAiB,EAAM,GACtB,IAEHE,GAAQ,KAIFhB,IACFH,EAAeoB,kBAAiB,GAChCpB,EAAeqB,cAAcnB,GAC7BF,EAAesB,eAAerB,GAC9BD,EAAeoB,kBAAiB,GACjC,GACA,CAACnB,EAAUC,EAAYF,IAE1BM,GAAS,KACP,GAAIH,GAAWoB,MAERvB,EAAewB,WAAY,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AAgBvF,EAAMsF,QAC9BiB,eACArG,OAAQF,EAAME,OACd2D,GAAI7D,EAAM6D,GACVzE,SAAUY,EAAMZ,YAIpB,OAAOqC,EAAAmB,cAAAnB,EAAAgF,SAAA,KAAGD,EAAe,ECddE,EAAiB1G,IAC5B,MAAMF,EAAEA,GAAM8D,IAEd,OAAOnC,EAAAmB,cAACyD,EAAMzG,OAAAC,OAAA,CAAAC,EAAGA,GAA8BE,GAAS,ECT7C2G,EAAaC,IACxB,MAAMjH,OAAEA,GAAWuD,KAEbO,SAAEA,GAAaH,IASrB,OAPAjD,GAAU,KACR,MAAMwG,EAAYD,eAAAA,EAAQ9F,KAAKwB,GAAM3C,EAAOmH,GAAGxE,EAAGmB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQxF,KAAK,OAEVzB,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 n,useEffect as t,useMemo as r,Suspense as o,useContext as s,useCallback as a,useRef as i}from"react";import{isSSR as c,getTranslateProps as l,getFallback as u,getFallbackArray as d}from"@tolgee/web";export*from"@tolgee/web";function g(e,o,s){const a=Boolean(o||s),[i]=n((()=>{return n=e,Object.assign(Object.assign({},n),{t(...e){const t=l(...e);return n.t(Object.assign(Object.assign({},t),{noWrap:!0}))}});var n})),[u,d]=n(a);return t((()=>{d(!1)}),[]),r((()=>{a&&(e.setEmitterActive(!1),e.addStaticData(s),e.changeLanguage(o),e.setEmitterActive(!0))}),[o,s,e]),n((()=>{if(a&&c()&&!e.isLoaded()){const n=e.getRequiredRecords(o).map((({namespace:e,language:n})=>e?`${e}:${n}`:n)).filter((e=>!(null==s?void 0:s[e])));console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${n.map((e=>`"${e}"`)).join(", ")}`)}})),u?i:e}const p={useSuspense:!0};let b;const m=()=>(b||(b=e.createContext(void 0)),b);let f;const v=({tolgee:r,options:s,children:a,fallback:i,staticData:c,language:l})=>{const[u,d]=n(!r.isLoaded());t((()=>{(null==f?void 0:f.run)!==r.run&&(f&&f.stop(),f=r,r.run().catch((e=>{console.error(e)})).finally((()=>{d(!1)})))}),[r]);const b=g(r,l,c),v=Object.assign(Object.assign({},p),s),j=m();return v.useSuspense?e.createElement(j.Provider,{value:{tolgee:b,options:v}},u?i:e.createElement(o,{fallback:i||null},a)):e.createElement(j.Provider,{value:{tolgee:b,options:v}},u?i:a)};let j;const h=e=>n=>(j={tolgee:n,options:Object.assign(Object.assign({},p),e)},n);const E=()=>{const e=m(),n=s(e)||j;if(!n)throw new Error("Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?");return n},O=()=>{const[e,t]=n(0);return{instance:e,rerender:a((()=>{t((e=>e+1))}),[t])}},y=(e,n)=>{const{tolgee:r,options:o}=E(),s=u(e),c=d(s).join(":"),l=Object.assign(Object.assign({},o),n),{rerender:g,instance:p}=O(),b=i(),m=i([]);m.current=[];const f=r.isLoaded(s);t((()=>{const e=r.onNsUpdate(g);return b.current=e,e.subscribeNs(s),m.current.forEach((n=>{e.subscribeNs(n)})),()=>{e.unsubscribe()}}),[c,r]),t((()=>(r.addActiveNs(s),()=>r.removeActiveNs(s))),[c,r]);const v=a((e=>{var n;const t=null!==(n=e.ns)&&void 0!==n?n:null==s?void 0:s[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(l.useSuspense&&!f)throw r.addActiveNs(s,!0);return{t:v,isLoading:!f}},N=(e,n)=>{const{t:t,isLoading:r}=y(e,n);return{t:a(((...e)=>{const n=l(...e);return t(n)}),[t]),isLoading:r}},A=n=>{if(!n)return;const t={};return Object.entries(n||{}).forEach((([n,r])=>{if("function"==typeof r)t[n]=e=>r(L(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,{},L(n)):e.cloneElement(o)}else t[n]=r})),t},L=n=>Array.isArray(n)?e.Children.toArray(n):n,k=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=L(n.t({key:t,params:A(n.params),defaultValue:r,noWrap:n.noWrap,ns:n.ns,language:n.language}));return e.createElement(e.Fragment,null,o)},w=n=>{const{t:t}=y();return e.createElement(k,Object.assign({t:t},n))},S=e=>{const{tolgee:n}=E(),{rerender:r}=O();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};export{h as GlobalContextPlugin,w as T,k as TBase,v as TolgeeProvider,m as getProviderInstance,S as useTolgee,g as useTolgeeSSR,N 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","getRequ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rB,OAPAtB,GAAU,KACR,MAAMoF,EAAYD,eAAAA,EAAQE,KAAKjF,GAAMZ,EAAO8F,GAAGlF,EAAGqB,KAClD,MAAO,KACL2D,SAAAA,EAAWxC,SAAS2C,GAAaA,EAAS1C,eAAc,CACzD,GACA,CAACsC,aAAA,EAAAA,EAAQhD,KAAK,OAEV3C,CAAM,WCcCgG,EACdC,EACAV,EACAW,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.mjs","sources":["../src/useTolgeeSSR.ts","../src/TolgeeProvider.tsx","../src/GlobalContextPlugin.tsx","../src/useTolgeeContext.ts","../src/hooks.ts","../src/useTranslateInternal.ts","../src/useTranslate.ts","../src/tagsTools.tsx","../src/TBase.tsx","../src/T.tsx","../src/useTolgee.ts"],"sourcesContent":["import {\n getTranslateProps,\n TolgeeInstance,\n TolgeeStaticData,\n isSSR,\n} from '@tolgee/web';\nimport { useEffect, useMemo, useState } from 'react';\n\nfunction getTolgeeWithDeactivatedWrapper(\n tolgee: TolgeeInstance\n): TolgeeInstance {\n return {\n ...tolgee,\n t(...args) {\n // @ts-ignore\n const props = getTranslateProps(...args);\n return tolgee.t({ ...props, noWrap: true });\n },\n };\n}\n\n/**\n * Updates tolgee static data and language, to be ready right away for the first render\n * and therefore compatible with SSR.\n *\n * It also ensures that the first render is done without wrapping and so it avoids\n * \"client different than server\" issues.\n *\n * If no language data and static data are provided no action is taken\n *\n * @param tolgeeInstance initialized Tolgee instance\n * @param language language that is obtained outside of Tolgee on the server and client\n * @param staticData static data for the language\n */\nexport function useTolgeeSSR(\n tolgeeInstance: TolgeeInstance,\n language?: string,\n staticData?: TolgeeStaticData | undefined\n) {\n const enabled = Boolean(language || staticData);\n\n const [noWrappingTolgee] = useState(() =>\n getTolgeeWithDeactivatedWrapper(tolgeeInstance)\n );\n\n const [initialRender, setInitialRender] = useState(enabled);\n\n useEffect(() => {\n setInitialRender(false);\n }, []);\n\n useMemo(() => {\n // we have to prepare tolgee before rendering children\n // so translations are available right away\n // events emitting must be off, to not trigger re-render while rendering\n if (enabled) {\n tolgeeInstance.setEmitterActive(false);\n tolgeeInstance.addStaticData(staticData);\n tolgeeInstance.changeLanguage(language!);\n tolgeeInstance.setEmitterActive(true);\n }\n }, [language, staticData, tolgeeInstance]);\n\n useState(() => {\n if (enabled && isSSR()) {\n // running this function only on first render\n if (!tolgeeInstance.isLoaded()) {\n // warning user, that static data provided are not sufficient\n // for proper SSR render\n const missingRecords = tolgeeInstance\n .getRequiredRecords(language)\n .map(({ namespace, language }) =>\n namespace ? `${namespace}:${language}` : language\n )\n .filter((key) => !staticData?.[key]);\n\n // eslint-disable-next-line no-console\n console.warn(\n `Tolgee: Missing records in \"staticData\" for proper SSR functionality: ${missingRecords.map((key) => `\"${key}\"`).join(', ')}`\n );\n }\n }\n });\n\n return initialRender ? noWrappingTolgee : tolgeeInstance;\n}\n","import React, { Suspense, useEffect, useState } from 'react';\nimport { TolgeeInstance, TolgeeStaticData } from '@tolgee/web';\nimport { ReactOptions, TolgeeReactContext } from './types';\nimport { useTolgeeSSR } from './useTolgeeSSR';\n\nexport const DEFAULT_REACT_OPTIONS: ReactOptions = {\n useSuspense: true,\n};\n\nlet ProviderInstance: React.Context<TolgeeReactContext | undefined>;\n\nexport const getProviderInstance = () => {\n if (!ProviderInstance) {\n ProviderInstance = React.createContext<TolgeeReactContext | undefined>(\n undefined\n );\n }\n\n return ProviderInstance;\n};\n\nlet LAST_TOLGEE_INSTANCE: TolgeeInstance | undefined = undefined;\n\nexport interface TolgeeProviderProps {\n children?: React.ReactNode;\n tolgee: TolgeeInstance;\n options?: ReactOptions;\n fallback?: React.ReactNode;\n /**\n * Hard set language to this value, use together with `staticData`\n */\n language?: string;\n /**\n * If provided, static data will be hard set to Tolgee cache for initial render\n */\n staticData?: TolgeeStaticData;\n}\n\nexport const TolgeeProvider: React.FC<TolgeeProviderProps> = ({\n tolgee,\n options,\n children,\n fallback,\n staticData,\n language,\n}) => {\n 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 tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);\n\n const optionsWithDefault = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n const TolgeeProviderContext = getProviderInstance();\n\n if (optionsWithDefault.useSuspense) {\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? (\n fallback\n ) : (\n <Suspense fallback={fallback || null}>{children}</Suspense>\n )}\n </TolgeeProviderContext.Provider>\n );\n }\n\n return (\n <TolgeeProviderContext.Provider\n value={{ tolgee: tolgeeSSR, options: optionsWithDefault }}\n >\n {loading ? fallback : children}\n </TolgeeProviderContext.Provider>\n );\n};\n","import type { TolgeePlugin } from '@tolgee/web';\nimport { DEFAULT_REACT_OPTIONS } from './TolgeeProvider';\nimport type { ReactOptions, TolgeeReactContext } from './types';\n\nlet globalContext: TolgeeReactContext | undefined;\n\nexport const GlobalContextPlugin =\n (options?: Partial<ReactOptions>): TolgeePlugin =>\n (tolgee) => {\n globalContext = {\n tolgee,\n options: { ...DEFAULT_REACT_OPTIONS, ...options },\n };\n return tolgee;\n };\n\nexport function getGlobalContext() {\n return globalContext;\n}\n","import { useContext } from 'react';\nimport { getGlobalContext } from './GlobalContextPlugin';\nimport { getProviderInstance } from './TolgeeProvider';\n\nexport const useTolgeeContext = () => {\n const TolgeeProviderContext = getProviderInstance();\n const context = useContext(TolgeeProviderContext) || getGlobalContext();\n if (!context) {\n throw new Error(\n \"Couldn't find tolgee instance, did you forgot to use `TolgeeProvider`?\"\n );\n }\n return context;\n};\n","import { useCallback, useState } from 'react';\n\nexport const useRerender = () => {\n const [instance, setCounter] = useState(0);\n\n const rerender = useCallback(() => {\n setCounter((num) => num + 1);\n }, [setCounter]);\n return { instance, rerender };\n};\n","import { useCallback, useEffect, useRef } from 'react';\nimport {\n SubscriptionSelective,\n TranslateProps,\n NsFallback,\n getFallbackArray,\n getFallback,\n} from '@tolgee/web';\n\nimport { useTolgeeContext } from './useTolgeeContext';\nimport { ReactOptions } from './types';\nimport { useRerender } from './hooks';\n\nexport const useTranslateInternal = (\n ns?: NsFallback,\n options?: ReactOptions\n) => {\n const { tolgee, options: defaultOptions } = useTolgeeContext();\n const namespaces = getFallback(ns);\n const namespacesJoined = getFallbackArray(namespaces).join(':');\n\n const currentOptions = {\n ...defaultOptions,\n ...options,\n };\n\n // dummy state to enable re-rendering\n const { rerender, instance } = useRerender();\n\n const subscriptionRef = useRef<SubscriptionSelective>();\n\n const subscriptionQueue = useRef([] as NsFallback[]);\n subscriptionQueue.current = [];\n\n const subscribeToNs = (ns: NsFallback) => {\n subscriptionQueue.current.push(ns);\n subscriptionRef.current?.subscribeNs(ns);\n };\n\n const isLoaded = tolgee.isLoaded(namespaces);\n\n useEffect(() => {\n const subscription = tolgee.onNsUpdate(rerender);\n subscriptionRef.current = subscription;\n subscription.subscribeNs(namespaces);\n subscriptionQueue.current.forEach((ns) => {\n subscription!.subscribeNs(ns);\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [namespacesJoined, tolgee]);\n\n useEffect(() => {\n tolgee.addActiveNs(namespaces);\n return () => tolgee.removeActiveNs(namespaces);\n }, [namespacesJoined, tolgee]);\n\n const t = useCallback(\n (props: TranslateProps<any>) => {\n const fallbackNs = props.ns ?? namespaces?.[0];\n subscribeToNs(fallbackNs);\n return tolgee.t({ ...props, ns: fallbackNs }) as any;\n },\n [tolgee, instance]\n );\n\n if (currentOptions.useSuspense && !isLoaded) {\n throw tolgee.addActiveNs(namespaces, true);\n }\n\n return { t, isLoading: !isLoaded };\n};\n","import { useCallback } from 'react';\nimport {\n TFnType,\n getTranslateProps,\n DefaultParamType,\n TranslationKey,\n} from '@tolgee/web';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { ReactOptions } from './types';\n\nexport interface UseTranslateResult {\n t: TFnType<DefaultParamType, string, TranslationKey>;\n isLoading: boolean;\n}\n\nexport const useTranslate = (\n ns?: string[] | string,\n options?: ReactOptions\n): UseTranslateResult => {\n const { t: tInternal, isLoading } = useTranslateInternal(ns, options);\n\n const t = useCallback(\n (...params: any) => {\n // @ts-ignore\n const props = getTranslateProps(...params);\n return tInternal(props);\n },\n [tInternal]\n );\n\n return { t, isLoading };\n};\n","import { TranslateParams } from '@tolgee/web';\nimport React from 'react';\n\nimport { ParamsTags } from './types';\n\nexport const wrapTagHandlers = (\n params: TranslateParams<ParamsTags> | undefined\n) => {\n if (!params) {\n return undefined;\n }\n\n const result: any = {};\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (typeof value === 'function') {\n result[key] = (chunk: any) => {\n return value(addReactKeys(chunk));\n };\n } else if (React.isValidElement(value as any)) {\n const el = value as React.ReactElement;\n result[key] = (chunk: any) => {\n return el.props.children === undefined && chunk?.length\n ? React.cloneElement(el, {}, addReactKeys(chunk))\n : React.cloneElement(el);\n };\n } else {\n result[key] = value;\n }\n });\n\n return result;\n};\n\nexport const addReactKeys = (\n val: React.ReactNode | React.ReactNode[] | undefined\n) => {\n if (Array.isArray(val)) {\n return React.Children.toArray(val);\n } else {\n return val;\n }\n};\n","import React from 'react';\nimport { addReactKeys, wrapTagHandlers } from './tagsTools';\nimport type { PropsWithKeyName, TBaseInterface } from './types';\n\nexport const TBase: TBaseInterface = (props) => {\n const key = (props as PropsWithKeyName).keyName || props.children;\n if (key === undefined) {\n // eslint-disable-next-line no-console\n console.error('T component: keyName not defined');\n }\n const defaultValue =\n props.defaultValue ||\n ((props as PropsWithKeyName).keyName ? props.children : undefined);\n\n const translation = addReactKeys(\n props.t({\n key: key!,\n params: wrapTagHandlers(props.params),\n defaultValue,\n noWrap: props.noWrap,\n ns: props.ns,\n language: props.language,\n })\n );\n\n return <>{translation}</>;\n};\n","import React from 'react';\nimport { ParamsTags, TProps } from './types';\n\nimport { useTranslateInternal } from './useTranslateInternal';\nimport { TFnType } from '@tolgee/web';\nimport { TBase } from './TBase';\n\ninterface TInterface {\n (props: TProps): JSX.Element;\n}\n\nexport const T: TInterface = (props) => {\n const { t } = useTranslateInternal();\n\n return <TBase t={t as TFnType<ParamsTags>} {...props} />;\n};\n","import { TolgeeEvent, TolgeeInstance } from '@tolgee/web';\nimport { useEffect } from 'react';\nimport { useRerender } from './hooks';\nimport { useTolgeeContext } from './useTolgeeContext';\n\nexport const useTolgee = (events?: TolgeeEvent[]): TolgeeInstance => {\n const { tolgee } = useTolgeeContext();\n\n const { rerender } = useRerender();\n\n useEffect(() => {\n const listeners = events?.map((e) => tolgee.on(e, rerender));\n return () => {\n listeners?.forEach((listener) => listener.unsubscribe());\n };\n }, [events?.join(':')]);\n\n return tolgee;\n};\n"],"names":["useTolgeeSSR","tolgeeInstance","language","staticData","enabled","Boolean","noWrappingTolgee","useState","getTolgeeWithDeactivatedWrapper","tolgee","Object","assign","t","args","props","getTranslateProps","noWrap","initialRender","setInitialRender","useEffect","useMemo","setEmitterActive","addStaticData","changeLanguage","isSSR","isLoaded","missingRecords","getRequiredRecords","map","namespace","filter","key","console","warn","join","DEFAULT_REACT_OPTIONS","useSuspense","ProviderInstance","getProviderInstance","React","createContext","undefined","LAST_TOLGEE_INSTANCE","TolgeeProvider","options","children","fallback","loading","setLoading","run","stop","catch","e","error","finally","tolgeeSSR","optionsWithDefault","TolgeeProviderContext","createElement","Provider","value","Suspense","globalContext","GlobalContextPlugin","useTolgeeContext","context","useContext","Error","useRerender","instance","setCounter","rerender","useCallback","num","useTranslateInternal","ns","defaultOptions","namespaces","getFallback","namespacesJoined","getFallbackArray","currentOptions","subscriptionRef","useRef","subscriptionQueue","current","subscription","onNsUpdate","subscribeNs","forEach","unsubscribe","addActiveNs","removeActiveNs","fallbackNs","_a","push","subscribeToNs","isLoading","useTranslate","tInternal","params","wrapTagHandlers","result","entries","chunk","addReactKeys","isValidElement","el","length","cloneElement","val","Array","isArray","Children","toArray","TBase","keyName","defaultValue","translation","Fragment","T","useTolgee","events","listeners","on","listener"],"mappings":"+PAkCgBA,EACdC,EACAC,EACAC,GAEA,MAAMC,EAAUC,QAAQH,GAAYC,IAE7BG,GAAoBC,GAAS,KAClCC,OAjCFC,EAiCkCR,EA/BlCS,OAAAC,OAAAD,OAAAC,OAAA,GACKF,GAAM,CACT,CAAAG,IAAKC,GAEH,MAAMC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E,EAAEF,EAAaD,IACxCjE,EAAMsE,aAAaF,EAE1B,MACCL,EAAOvE,GAAO6B,CACf,IAGI0C,CAAM,EAGFG,EACXK,GAEIC,MAAMC,QAAQF,GACTvE,EAAM0E,SAASC,QAAQJ,GAEvBA,ECpCEK,EAAyBrG,IACpC,MAAMiB,EAAOjB,EAA2BsG,SAAWtG,EAAM+B,cAC7CJ,IAARV,GAEFC,QAAQqB,MAAM,oCAEhB,MAAMgE,EACJvG,EAAMuG,eACJvG,EAA2BsG,QAAUtG,EAAM+B,cAAWJ,GAEpD6E,EAAcb,EAClB3F,EAAMF,EAAE,CACNmB,IAAKA,EACLqE,OAAQC,EAAgBvF,EAAMsF,QAC9BiB,eACArG,OAAQF,EAAME,OACd2D,GAAI7D,EAAM6D,GACVzE,SAAUY,EAAMZ,YAIpB,OAAOqC,EAAAmB,cAAAnB,EAAAgF,SAAA,KAAGD,EAAe,ECddE,EAAiB1G,IAC5B,MAAMF,EAAEA,GAAM8D,IAEd,OAAOnC,EAAAmB,cAACyD,EAAMzG,OAAAC,OAAA,CAAAC,EAAGA,GAA8BE,GAAS,ECT7C2G,EAAaC,IACxB,MAAMjH,OAAEA,GAAWuD,KAEbO,SAAEA,GAAaH,IASrB,OAPAjD,GAAU,KACR,MAAMwG,EAAYD,eAAAA,EAAQ9F,KAAKwB,GAAM3C,EAAOmH,GAAGxE,EAAGmB,KAClD,MAAO,KACLoD,SAAAA,EAAWlC,SAASoC,GAAaA,EAASnC,eAAc,CACzD,GACA,CAACgC,aAAA,EAAAA,EAAQxF,KAAK,OAEVzB,CAAM"}
@@ -1,7 +1,63 @@
1
- import React, { useState, useEffect, Suspense, useContext, useCallback, useRef, useMemo } from 'react';
2
- import { getFallback, getFallbackArray, getTranslateProps } from '@tolgee/web';
1
+ import React, { useState, useEffect, useMemo, Suspense, useContext, useCallback, useRef } from 'react';
2
+ import { isSSR, getTranslateProps, getFallback, getFallbackArray } from '@tolgee/web';
3
3
  export * from '@tolgee/web';
4
4
 
5
+ function getTolgeeWithDeactivatedWrapper(tolgee) {
6
+ return Object.assign(Object.assign({}, tolgee), { t(...args) {
7
+ // @ts-ignore
8
+ const props = getTranslateProps(...args);
9
+ return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
10
+ } });
11
+ }
12
+ /**
13
+ * Updates tolgee static data and language, to be ready right away for the first render
14
+ * and therefore compatible with SSR.
15
+ *
16
+ * It also ensures that the first render is done without wrapping and so it avoids
17
+ * "client different than server" issues.
18
+ *
19
+ * If no language data and static data are provided no action is taken
20
+ *
21
+ * @param tolgeeInstance initialized Tolgee instance
22
+ * @param language language that is obtained outside of Tolgee on the server and client
23
+ * @param staticData static data for the language
24
+ */
25
+ function useTolgeeSSR(tolgeeInstance, language, staticData) {
26
+ const enabled = Boolean(language || staticData);
27
+ const [noWrappingTolgee] = useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
28
+ const [initialRender, setInitialRender] = useState(enabled);
29
+ useEffect(() => {
30
+ setInitialRender(false);
31
+ }, []);
32
+ useMemo(() => {
33
+ // we have to prepare tolgee before rendering children
34
+ // so translations are available right away
35
+ // events emitting must be off, to not trigger re-render while rendering
36
+ if (enabled) {
37
+ tolgeeInstance.setEmitterActive(false);
38
+ tolgeeInstance.addStaticData(staticData);
39
+ tolgeeInstance.changeLanguage(language);
40
+ tolgeeInstance.setEmitterActive(true);
41
+ }
42
+ }, [language, staticData, tolgeeInstance]);
43
+ useState(() => {
44
+ if (enabled && isSSR()) {
45
+ // running this function only on first render
46
+ if (!tolgeeInstance.isLoaded()) {
47
+ // warning user, that static data provided are not sufficient
48
+ // for proper SSR render
49
+ const missingRecords = tolgeeInstance
50
+ .getRequiredRecords(language)
51
+ .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
52
+ .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
53
+ // eslint-disable-next-line no-console
54
+ console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
55
+ }
56
+ }
57
+ });
58
+ return initialRender ? noWrappingTolgee : tolgeeInstance;
59
+ }
60
+
5
61
  const DEFAULT_REACT_OPTIONS = {
6
62
  useSuspense: true,
7
63
  };
@@ -13,7 +69,7 @@ const getProviderInstance = () => {
13
69
  return ProviderInstance;
14
70
  };
15
71
  let LAST_TOLGEE_INSTANCE = undefined;
16
- const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
72
+ const TolgeeProvider = ({ tolgee, options, children, fallback, staticData, language, }) => {
17
73
  const [loading, setLoading] = useState(!tolgee.isLoaded());
18
74
  // prevent restarting tolgee unnecesarly
19
75
  // however if the instance change on hot-reloading
@@ -35,12 +91,13 @@ const TolgeeProvider = ({ tolgee, options, children, fallback, }) => {
35
91
  });
36
92
  }
37
93
  }, [tolgee]);
94
+ const tolgeeSSR = useTolgeeSSR(tolgee, language, staticData);
38
95
  const optionsWithDefault = Object.assign(Object.assign({}, DEFAULT_REACT_OPTIONS), options);
39
96
  const TolgeeProviderContext = getProviderInstance();
40
97
  if (optionsWithDefault.useSuspense) {
41
- return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? (fallback) : (React.createElement(Suspense, { fallback: fallback || null }, children))));
98
+ return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? (fallback) : (React.createElement(Suspense, { fallback: fallback || null }, children))));
42
99
  }
43
- return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee, options: optionsWithDefault } }, loading ? fallback : children));
100
+ return (React.createElement(TolgeeProviderContext.Provider, { value: { tolgee: tolgeeSSR, options: optionsWithDefault } }, loading ? fallback : children));
44
101
  };
45
102
 
46
103
  let globalContext;
@@ -195,54 +252,5 @@ const useTolgee = (events) => {
195
252
  return tolgee;
196
253
  };
197
254
 
198
- function getTolgeeWithDeactivatedWrapper(tolgee) {
199
- return Object.assign(Object.assign({}, tolgee), { t(...args) {
200
- // @ts-ignore
201
- const props = getTranslateProps(...args);
202
- return tolgee.t(Object.assign(Object.assign({}, props), { noWrap: true }));
203
- } });
204
- }
205
- /**
206
- * Updates tolgee static data and language, to be ready right away for the first render
207
- * and therefore compatible with SSR.
208
- *
209
- * It also ensures that the first render is done without wrapping and so it avoids
210
- * "client different than server" issues.
211
- *
212
- * @param tolgeeInstance initialized Tolgee instance
213
- * @param language language that is obtained outside of Tolgee on the server and client
214
- * @param staticData static data for the language
215
- */
216
- function useTolgeeSSR(tolgeeInstance, language, staticData) {
217
- const [noWrappingTolgee] = useState(() => getTolgeeWithDeactivatedWrapper(tolgeeInstance));
218
- const [initialRender, setInitialRender] = useState(true);
219
- useEffect(() => {
220
- setInitialRender(false);
221
- }, []);
222
- useMemo(() => {
223
- // we have to prepare tolgee before rendering children
224
- // so translations are available right away
225
- // events emitting must be off, to not trigger re-render while rendering
226
- tolgeeInstance.setEmitterActive(false);
227
- tolgeeInstance.addStaticData(staticData);
228
- tolgeeInstance.changeLanguage(language);
229
- tolgeeInstance.setEmitterActive(true);
230
- }, [language, staticData, tolgeeInstance]);
231
- useState(() => {
232
- // running this function only on first render
233
- if (!tolgeeInstance.isLoaded()) {
234
- // warning user, that static data provided are not sufficient
235
- // for proper SSR render
236
- const missingRecords = tolgeeInstance
237
- .getRequiredRecords(language)
238
- .map(({ namespace, language }) => namespace ? `${namespace}:${language}` : language)
239
- .filter((key) => !(staticData === null || staticData === void 0 ? void 0 : staticData[key]));
240
- // eslint-disable-next-line no-console
241
- console.warn(`Tolgee: Missing records in "staticData" for proper SSR functionality: ${missingRecords.map((key) => `"${key}"`).join(', ')}`);
242
- }
243
- });
244
- return initialRender ? noWrappingTolgee : tolgeeInstance;
245
- }
246
-
247
255
  export { GlobalContextPlugin, T, TBase, TolgeeProvider, getProviderInstance, useTolgee, useTolgeeSSR, useTranslate };
248
256
  //# sourceMappingURL=tolgee-react.esm.mjs.map