|
| 1 | +import React, { createContext, useCallback, useContext, useEffect, useMemo } from "react"; |
| 2 | + |
| 3 | +import { useLocalStorage } from "hooks/useLocalStorage"; |
| 4 | + |
| 5 | +export type SupportedLangs = "en" | "es" | "zh" | "fr" | "hi" | "ko" | "ja"; |
| 6 | + |
| 7 | +interface ITranslate { |
| 8 | + currentLang: SupportedLangs; |
| 9 | + setLang: (lang: SupportedLangs) => void; |
| 10 | +} |
| 11 | +const TranslateContext = createContext<ITranslate | undefined>(undefined); |
| 12 | + |
| 13 | +export const useTranslate = () => { |
| 14 | + const context = useContext(TranslateContext); |
| 15 | + if (!context) { |
| 16 | + throw new Error("Context Provider not found."); |
| 17 | + } |
| 18 | + return context; |
| 19 | +}; |
| 20 | + |
| 21 | +export const TranslateProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { |
| 22 | + const [currentLang, setCurrentLang] = useLocalStorage<SupportedLangs>("lang", "en"); |
| 23 | + |
| 24 | + useEffect(() => { |
| 25 | + try { |
| 26 | + // Check if the Google Translate script is already in the document |
| 27 | + const existingScript = document.querySelector('script[src*="translate.google.com/translate_a/element.js"]'); |
| 28 | + if (!existingScript) { |
| 29 | + const addScript = document.createElement("script"); |
| 30 | + addScript.setAttribute("src", "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"); |
| 31 | + document.body.appendChild(addScript); |
| 32 | + |
| 33 | + //@ts-expect-error will exist |
| 34 | + window.googleTranslateElementInit = () => { |
| 35 | + //@ts-expect-error will exist |
| 36 | + new window.google.translate.TranslateElement( |
| 37 | + { |
| 38 | + pageLanguage: "en", |
| 39 | + includedLanguages: "en,es,hi,ja,zh,fr,ko", // Include all languages you need here |
| 40 | + }, |
| 41 | + "google_translate_element" |
| 42 | + ); |
| 43 | + }; |
| 44 | + } |
| 45 | + } catch (err) { |
| 46 | + // eslint-disable-next-line no-console |
| 47 | + console.log("Error injecting google translate script", err); |
| 48 | + } |
| 49 | + }, []); |
| 50 | + |
| 51 | + const setLang = useCallback( |
| 52 | + (cValue: SupportedLangs) => { |
| 53 | + setCurrentLang(cValue); |
| 54 | + document.cookie = "googtrans" + "=" + `/en/${cValue}` + ";" + "Session" + ";path=/"; |
| 55 | + window.location.reload(); |
| 56 | + }, |
| 57 | + [setCurrentLang] |
| 58 | + ); |
| 59 | + |
| 60 | + return ( |
| 61 | + <TranslateContext.Provider value={useMemo(() => ({ currentLang, setLang }), [currentLang, setLang])}> |
| 62 | + <div id="google_translate_element"></div> |
| 63 | + {children} |
| 64 | + </TranslateContext.Provider> |
| 65 | + ); |
| 66 | +}; |
| 67 | + |
| 68 | +export default TranslateProvider; |
0 commit comments