Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC: New language handling #1758

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 16 additions & 94 deletions src/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
import "./style/index.css";
//@ts-ignore
import queryString from "query-string";
import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react";
import { ReactNode } from "react";
import { useDeviceSelectors } from "react-device-detect";
import { createRoot, hydrateRoot } from "react-dom/client";
import { HelmetProvider } from "react-helmet-async";
import { I18nextProvider, useTranslation } from "react-i18next";
import { I18nextProvider } from "react-i18next";
import { BrowserRouter, MemoryRouter } from "react-router-dom";
import { ApolloProvider, useApolloClient } from "@apollo/client";
import { ApolloProvider } from "@apollo/client";
import createCache from "@emotion/cache";
import { CacheProvider } from "@emotion/react";
import "@fontsource/source-code-pro/400-italic.css";
Expand All @@ -32,16 +32,14 @@ import "@fontsource/source-serif-pro/700.css";
import "@fontsource/source-serif-pro/index.css";
// @ts-ignore
import ErrorReporter from "@ndla/error-reporter";
import { i18nInstance } from "@ndla/ui";
import { getCookie, setCookie } from "@ndla/util";
import App from "./App";
import { VersionHashProvider } from "./components/VersionHashContext";
import { getDefaultLocale } from "./config";
import { EmotionCacheKey, STORED_LANGUAGE_COOKIE_KEY } from "./constants";
import { getLocaleInfoFromPath, initializeI18n, isValidLocale, supportedLanguages } from "./i18n";
import { EmotionCacheKey } from "./constants";
import { getLocaleInfoFromPath, initializeI18n, isValidLocale } from "./i18n";
import { NDLAWindow } from "./interfaces";
import { i18nInstance } from "./tempI18nClone";
import { UserAgentProvider } from "./UserAgentContext";
import { createApolloClient, createApolloLinks } from "./util/apiHelpers";
import { createApolloClient } from "./util/apiHelpers";

declare global {
interface Window extends NDLAWindow {}
Expand All @@ -51,10 +49,10 @@ const {
DATA: { config, serverPath, serverQuery },
} = window;

const { basepath, abbreviation } = getLocaleInfoFromPath(serverPath ?? "");
const { basepath } = getLocaleInfoFromPath(serverPath ?? "");

const paths = window.location.pathname.split("/");
const basename = isValidLocale(paths[1] ?? "") ? `${paths[1]}` : undefined;
const lang = isValidLocale(paths[1] ?? "") ? `${paths[1]}` : undefined;

const { versionHash } = queryString.parse(window.location.search);

Expand All @@ -64,17 +62,7 @@ const locationFromServer = {
search: serverQueryString ? `?${serverQueryString}` : "",
};

const maybeStoredLanguage = getCookie(STORED_LANGUAGE_COOKIE_KEY, document.cookie);
// Set storedLanguage to a sane value if non-existent
if (maybeStoredLanguage === null || maybeStoredLanguage === undefined) {
setCookie({
cookieName: STORED_LANGUAGE_COOKIE_KEY,
cookieValue: abbreviation,
lax: true,
});
}
const storedLanguage = getCookie(STORED_LANGUAGE_COOKIE_KEY, document.cookie)!;
const i18n = initializeI18n(i18nInstance, storedLanguage);
const i18n = initializeI18n(i18nInstance, lang ?? config.defaultLocale);

window.errorReporter = ErrorReporter.getInstance({
logglyApiKey: config.logglyApiKey,
Expand All @@ -83,7 +71,7 @@ window.errorReporter = ErrorReporter.getInstance({
ignoreUrls: [],
});

const client = createApolloClient(storedLanguage, versionHash);
const client = createApolloClient(lang, versionHash);
const cache = createCache({ key: EmotionCacheKey });

// Use memory router if running under google translate
Expand All @@ -99,82 +87,16 @@ const RouterComponent = ({ children, base }: RCProps) =>
isGoogleUrl ? (
<MemoryRouter initialEntries={[locationFromServer]}>{children}</MemoryRouter>
) : (
<BrowserRouter key={base} basename={base}>
{children}
</BrowserRouter>
<BrowserRouter basename={base}>{children}</BrowserRouter>
);

const constructNewPath = (newLocale?: string) => {
const regex = new RegExp(`\\/(${supportedLanguages.join("|")})($|\\/)`, "");
const path = window.location.pathname.replace(regex, "");
const fullPath = path.startsWith("/") ? path : `/${path}`;
const localePrefix = newLocale ? `/${newLocale}` : "";
return `${localePrefix}${fullPath}${window.location.search}`;
};

const useReactPath = () => {
const [path, setPath] = useState("");
const listenToPopstate = () => {
const winPath = window.location.pathname;
setPath(winPath);
};
useEffect(() => {
window.addEventListener("popstate", listenToPopstate);
window.addEventListener("pushstate", listenToPopstate);
return () => {
window.removeEventListener("popstate", listenToPopstate);
window.removeEventListener("pushstate", listenToPopstate);
};
}, []);
return path;
};

const LanguageWrapper = ({ basename }: { basename?: string }) => {
const { i18n } = useTranslation();
const [base, setBase] = useState(basename ?? "");
const firstRender = useRef(true);
const client = useApolloClient();
const windowPath = useReactPath();
const UserAgentWrapper = ({ basename }: { basename?: string }) => {
const [selectors] = useDeviceSelectors(window.navigator.userAgent);

i18n.on("languageChanged", (lang) => {
setCookie({
cookieName: STORED_LANGUAGE_COOKIE_KEY,
cookieValue: lang,
lax: true,
});
client.resetStore();
client.setLink(createApolloLinks(lang, versionHash));
document.documentElement.lang = lang;
});

// handle path changes when the language is changed
useLayoutEffect(() => {
if (firstRender.current) {
firstRender.current = false;
} else {
window.history.replaceState("", "", constructNewPath(i18n.language));
setBase(i18n.language);
}
}, [i18n.language]);

// handle initial redirect if URL has wrong or missing locale prefix.
// only relevant when disableSSR=true
useLayoutEffect(() => {
const storedLanguage = getCookie(STORED_LANGUAGE_COOKIE_KEY, document.cookie)!;
if (storedLanguage === getDefaultLocale() && !base) return;
if (isValidLocale(storedLanguage) && storedLanguage === base) {
setBase(storedLanguage);
}
if (window.location.pathname.includes("/login/success")) return;
setBase(storedLanguage);
window.history.replaceState("", "", constructNewPath(storedLanguage));
}, [base, windowPath]);

return (
<UserAgentProvider value={selectors}>
<RouterComponent key={base} base={base}>
<App base={base} />
<RouterComponent base={basename ?? ""}>
<App base={basename} />
</RouterComponent>
</UserAgentProvider>
);
Expand All @@ -196,7 +118,7 @@ renderOrHydrate(
<ApolloProvider client={client}>
<CacheProvider value={cache}>
<VersionHashProvider value={versionHash}>
<LanguageWrapper basename={basename} />
<UserAgentWrapper basename={lang} />
</VersionHashProvider>
</CacheProvider>
</ApolloProvider>
Expand Down
10 changes: 7 additions & 3 deletions src/containers/Masthead/MastheadContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*
*/

import { useContext } from "react";
import { useCallback, useContext } from "react";

import { useTranslation } from "react-i18next";
import { gql } from "@apollo/client";
Expand All @@ -23,9 +23,9 @@ import FeideLoginButton from "../../components/FeideLoginButton";
import config from "../../config";
import { SKIP_TO_CONTENT_ID } from "../../constants";
import { GQLMastHeadQuery, GQLMastHeadQueryVariables } from "../../graphqlTypes";
import { supportedLanguages } from "../../i18n";
import { useIsNdlaFilm, useUrnIds } from "../../routeHelpers";
import { useGraphQuery } from "../../util/runQueries";
import { constructNewPath } from "../../util/urlHelper";
import ErrorBoundary from "../ErrorPage/ErrorBoundary";

const FeideLoginLabel = styled.span`
Expand Down Expand Up @@ -91,6 +91,10 @@ const MastheadContainer = () => {
number: alert.number,
}));

const onChangeLanguage = useCallback((lang: string) => {
window.location.href = constructNewPath(window.location.pathname, lang);
}, []);

return (
<ErrorBoundary>
<Masthead
Expand All @@ -109,7 +113,7 @@ const MastheadContainer = () => {
<ButtonWrapper>
<MastheadSearch subject={data?.subject} />
<LanguageSelectWrapper>
<LanguageSelector inverted={ndlaFilm} locales={supportedLanguages} onSelect={i18n.changeLanguage} />
<LanguageSelector inverted={ndlaFilm} locales={["nb", "nn"]} onSelect={onChangeLanguage} />
</LanguageSelectWrapper>
{config.feideEnabled && (
<FeideLoginButton>
Expand Down
45 changes: 36 additions & 9 deletions src/containers/Page/components/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*
*/

import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { css } from "@emotion/react";
import styled from "@emotion/styled";
Expand All @@ -14,7 +15,7 @@ import { colors, spacing, stackOrder } from "@ndla/core";
import { Facebook, HelpCircleOutline, Instagram, LinkedIn, EmailOutline, Youtube } from "@ndla/icons/common";
import { Footer, FooterText, EditorName, LanguageSelector } from "@ndla/ui";
import config from "../../../config";
import { supportedLanguages } from "../../../i18n";
import { constructNewPath } from "../../../util/urlHelper";

const FooterTextWrapper = styled.div`
p:first-of-type {
Expand All @@ -25,6 +26,18 @@ const FooterTextWrapper = styled.div`
}
`;

const LanguageLinkWrappers = styled.div`
display: flex;
justify-content: center;
gap: ${spacing.small};
a {
color: ${colors.white};
&:hover {
color: ${colors.white};
}
}
`;

const FooterWrapper = () => {
const { t, i18n } = useTranslation();
const zendeskLanguage = i18n.language === "nb" || i18n.language === "nn" ? "no" : i18n.language;
Expand Down Expand Up @@ -128,6 +141,10 @@ const FooterWrapper = () => {
height: 20px;
`;

const onChangeLanguage = useCallback((lang: string) => {
window.location.href = constructNewPath(window.location.pathname, lang);
}, []);

return (
<>
{config.zendeskWidgetKey && (
Expand All @@ -146,19 +163,29 @@ const FooterWrapper = () => {
languageSelector={
<LanguageSelector
inverted
locales={supportedLanguages}
onSelect={i18n.changeLanguage}
locales={["nb", "nn"]}
onSelect={onChangeLanguage}
triggerId="languageSelectorFooter"
/>
}
privacyLinks={privacyLinks}
>
<FooterTextWrapper>
<FooterText>
<EditorName title={t("footer.editorInChief")} name="Sigurd Trageton" />
</FooterText>
<FooterText>{t("footer.info")}</FooterText>
</FooterTextWrapper>
<>
<LanguageLinkWrappers>
<a href="/en/subject:27e8623d-c092-4f00-9a6f-066438d6c466" rel="noopener noreferrer">
Українська
</a>
<a href="/se/subject:e474cd73-5b8a-42cf-b0f1-b027e522057c" rel="noopener noreferrer">
Davvisámegiella
</a>
</LanguageLinkWrappers>
<FooterTextWrapper>
<FooterText>
<EditorName title={t("footer.editorInChief")} name="Sigurd Trageton" />
</FooterText>
<FooterText>{t("footer.info")}</FooterText>
</FooterTextWrapper>
</>
</Footer>
</>
);
Expand Down
30 changes: 4 additions & 26 deletions src/server/routes/defaultRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,13 @@ import { ApolloProvider } from "@apollo/client";
import createCache from "@emotion/cache";
import { CacheProvider } from "@emotion/react";
import { i18nInstance } from "@ndla/ui";
import { getCookie } from "@ndla/util";

import App from "../../App";
import RedirectContext, { RedirectInfo } from "../../components/RedirectContext";
import { VersionHashProvider } from "../../components/VersionHashContext";
import config from "../../config";
import { EmotionCacheKey, STORED_LANGUAGE_COOKIE_KEY } from "../../constants";
import { EmotionCacheKey } from "../../constants";
import { getLocaleInfoFromPath, initializeI18n, isValidLocale } from "../../i18n";
import { LocaleType } from "../../interfaces";
import { TEMPORARY_REDIRECT } from "../../statusCodes";
import { UserAgentProvider } from "../../UserAgentContext";
import { createApolloClient } from "../../util/apiHelpers";
import { Assets } from "../helpers/Document";
Expand All @@ -51,12 +48,11 @@ const disableSSR = (req: Request) => {
async function doRender(req: Request) {
//@ts-ignore
global.assets = assets; // used for including mathjax js in pages with math
const resCookie = req.headers["cookie"] ?? "";
const userAgent = req.headers["user-agent"];
const userAgentSelectors = userAgent ? getSelectorsByUserAgent(userAgent) : undefined;
const versionHash = typeof req.query.versionHash === "string" ? req.query.versionHash : undefined;
const { basename, abbreviation } = getLocaleInfoFromPath(req.path);
const locale = getCookieLocaleOrFallback(resCookie, abbreviation);
const locale = isValidLocale(abbreviation) ? abbreviation : config.defaultLocale;
const noSSR = disableSSR(req);

const client = createApolloClient(locale, versionHash);
Expand Down Expand Up @@ -112,25 +108,7 @@ async function doRender(req: Request) {
};
}

function getCookieLocaleOrFallback(resCookie: string, abbreviation: LocaleType) {
const cookieLocale = getCookie(STORED_LANGUAGE_COOKIE_KEY, resCookie) ?? "";
if (cookieLocale.length && isValidLocale(cookieLocale)) {
return cookieLocale;
}
return abbreviation;
}

export async function defaultRoute(req: Request) {
const resCookie = req.headers["cookie"] ?? "";
const { basename, basepath, abbreviation } = getLocaleInfoFromPath(req.originalUrl);
const locale = getCookieLocaleOrFallback(resCookie, abbreviation);
if ((locale === "nb" && basename === "") || locale === basename) {
const { html, context, docProps, helmetContext } = await doRender(req);
return renderHtml(html, context, docProps, helmetContext);
}

return {
status: TEMPORARY_REDIRECT,
data: { Location: `/${locale}${basepath}` },
};
const { html, context, docProps, helmetContext } = await doRender(req);
return renderHtml(html, context, docProps, helmetContext);
}
Loading
Loading