app-with-translation.tsx 9.7 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4
/* eslint-disable @typescript-eslint/no-explicit-any */

import {I18nextProvider, withSSR} from 'react-i18next';
import {isServer, lngFromReq, lngPathCorrector, lngsToLoad} from '../utils';
5 6

import {AppContext} from 'next/app';
7
import {I18n} from '../../types';
8 9 10 11 12 13
import NextI18Next from '../index';
import {NextPageContext} from 'next';
import {NextStaticProvider} from '../components';
import React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import {withRouter} from 'next/router';
P
Peter Pan 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

interface Props {
    initialLanguage: string;
    initialI18nStore: any;
    i18nServerInstance: any;
}

interface WrappedComponentProps {
    pageProps: {
        namespacesRequired?: string[];
    };
}

type I18nReq = {
    i18n?: I18n;
    locale?: string;
    lng?: string;
    language?: string;
};

type I18nRes = {
    locals?: {
        language?: string;
        languageDir?: string;
    };
};

P
Peter Pan 已提交
41
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
42
export const appWithTranslation = function (this: NextI18Next, WrappedComponent: any) {
P
Peter Pan 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55
    const WrappedComponentWithSSR = withSSR()(WrappedComponent);
    const {config, i18n} = this;
    const consoleMessage = this.consoleMessage.bind(this);

    const clientLoadNamespaces = (lng: string, namespaces: string[]) =>
        Promise.all(namespaces.filter(ns => !i18n.hasResourceBundle(lng, ns)).map(ns => i18n.reloadResources(lng, ns)));

    class AppWithTranslation extends React.Component<Props> {
        constructor(props: any) {
            super(props);
            if (!isServer()) {
                const changeLanguageCallback = (prevLng: string, newLng: string) => {
                    const {router} = props;
P
Peter Pan 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68
                    const {query} = router;
                    let {pathname, asPath} = router;

                    if (process.env.PUBLIC_PATH) {
                        const publicPath = process.env.PUBLIC_PATH;
                        if (pathname.indexOf(publicPath) === 0) {
                            pathname = pathname.replace(publicPath, '');
                        }
                        if (asPath.indexOf(publicPath) === 0) {
                            asPath = asPath.replace(publicPath, '');
                        }
                    }

P
Peter Pan 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
                    const routeInfo = {pathname, query};

                    if ((i18n as any).initializedLanguageOnce && typeof newLng === 'string' && prevLng !== newLng) {
                        const {as, href} = lngPathCorrector(config, {as: asPath, href: routeInfo}, newLng);
                        router.replace(href, as, {shallow: config.shallowRender});
                    }
                };

                const changeLanguage = i18n.changeLanguage.bind(i18n);
                i18n.changeLanguage = async (newLng: string, callback = () => null) => {
                    const prevLng = i18n.language;
                    if (typeof newLng === 'string' && (i18n as any).initializedLanguageOnce === true) {
                        const usedNamespaces = Object.entries((i18n.reportNamespaces as any).usedNamespaces)
                            .filter(x => x[1] === true)
                            .map(x => x[0]);
                        await clientLoadNamespaces(newLng, usedNamespaces);
                    }
                    return changeLanguage(newLng, () => {
                        changeLanguageCallback(prevLng, newLng);
                        callback(null, i18n.t);
                    });
                };
            }
        }

        static async getInitialProps(ctx: AppContext) {
            let wrappedComponentProps: WrappedComponentProps = {pageProps: {}};
            if (WrappedComponent.getInitialProps) {
                wrappedComponentProps = await WrappedComponent.getInitialProps(ctx);
            }
            if (typeof wrappedComponentProps.pageProps === 'undefined') {
                consoleMessage(
                    'error',
                    'If you have a getInitialProps method in your custom _app.js file, you must explicitly return pageProps. For more information, see: https://github.com/zeit/next.js#custom-app'
                );
            }

            /*
                Initiate vars to return
            */
            const req = ctx.ctx.req as (NextPageContext['req'] & I18nReq) | undefined;
            let initialI18nStore: Record<string, any> = {};
            let initialLanguage = null;
            let i18nServerInstance = null;

            if (req && !req.i18n) {
                const {router} = ctx;
                const result = router.asPath.match(/^\/(.*?)\//);
117
                const lng = result ? result[1] : config.defaultLanguage;
P
Peter Pan 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
                req.i18n = i18n.cloneInstance({initImmediate: false, lng});
                const res = ctx.ctx.res as (NextPageContext['res'] & I18nRes) | undefined;
                const setContextLocale = (lng?: string) => {
                    // SEE: i18n-express-middleware
                    req.language = req.locale = req.lng = lng;
                    if (res) {
                        res.locals = res.locals || {};
                        res.locals.language = lng;
                        res.locals.languageDir = i18n.dir(lng);
                    }
                };
                setContextLocale(lng);
                i18n.on('languageChanged', setContextLocale);
            }

            /*
                Step 1: Determine initial language
            */
            if (req && req.i18n) {
                initialLanguage = lngFromReq(req as any);

                /*
                    Perform a lang change in case we're not on the right lang
                */
                await req.i18n.changeLanguage(initialLanguage as string);
            } else if (Array.isArray(i18n.languages) && i18n.languages.length > 0) {
                initialLanguage = i18n.language;
            }

            /*
                Step 2: Determine namespace dependencies
            */
            let namespacesRequired = config.ns;
            if (Array.isArray(wrappedComponentProps.pageProps.namespacesRequired)) {
                ({namespacesRequired} = wrappedComponentProps.pageProps);
            } else {
                consoleMessage(
                    'warn',
156 157 158
                    `You have not declared a namespacesRequired array on your page-level component: ${
                        ctx.Component.displayName || ctx.Component.name || 'Component'
                    }. This will cause all namespaces to be sent down to the client, possibly negatively impacting the performance of your app. For more info, see: https://github.com/isaachinman/next-i18next#4-declaring-namespace-dependencies`
P
Peter Pan 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
                );
            }

            /*
                We must always send down the defaultNS, otherwise
                the client will trigger a request for it and issue
                the "Did not expect server HTML to contain a <h1> in <div>"
                error
            */
            if (typeof config.defaultNS === 'string' && !(namespacesRequired as string[]).includes(config.defaultNS)) {
                (namespacesRequired as string[]).push(config.defaultNS);
            }

            /*
                Step 3: Perform data fetching, depending on environment
            */
            if (req && req.i18n) {
                /*
                    Detect the languages to load based upon the fallbackLng configuration
                */
                const {fallbackLng} = config;
                const languagesToLoad = lngsToLoad(initialLanguage, fallbackLng, config.otherLanguages);

                /*
183
                    Initialize the store with the languagesToLoad and
P
Peter Pan 已提交
184 185 186 187 188 189 190 191 192 193 194
                    necessary namespaces needed to render this specific tree
                */
                languagesToLoad.forEach(lng => {
                    initialI18nStore[lng as string] = {};
                    (namespacesRequired as string[]).forEach(ns => {
                        initialI18nStore[lng as string][ns] =
                            ((req.i18n as I18n).services.resourceStore.data[lng as string] || {})[ns] || {};
                    });
                });
            } else if (Array.isArray(i18n.languages) && i18n.languages.length > 0) {
                /*
195
                    Load newly-required translations if changing route client side
P
Peter Pan 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
                */
                await clientLoadNamespaces(i18n.languages[0], namespacesRequired as string[]);

                initialI18nStore = (i18n as any).store.data;
            }

            /*
                Step 4: Overwrite i18n.toJSON method to be able to serialize the instance
            */
            if (req && req.i18n) {
                (req.i18n as any).toJSON = () => null;
                i18nServerInstance = req.i18n;
            }

            /*
                `pageProps` will get serialized automatically by NextJs
            */
            return {
                initialI18nStore,
                initialLanguage,
                i18nServerInstance,
                ...wrappedComponentProps
            };
        }

        render() {
            const {initialLanguage, initialI18nStore, i18nServerInstance} = this.props;

            return (
                <I18nextProvider i18n={i18nServerInstance || i18n}>
                    <NextStaticProvider>
                        <WrappedComponentWithSSR
                            initialLanguage={initialLanguage}
                            initialI18nStore={initialI18nStore}
                            {...this.props}
                        />
                    </NextStaticProvider>
                </I18nextProvider>
            );
        }
    }

    return hoistNonReactStatics(withRouter(AppWithTranslation as any), WrappedComponent, {getInitialProps: true});
};