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

New language handling #1832

Draft
wants to merge 6 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
2 changes: 2 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import config from "./config";
import AboutPage from "./containers/AboutPage/AboutPage";
import AccessDenied from "./containers/AccessDeniedPage/AccessDeniedPage";
import AllSubjectsPage from "./containers/AllSubjectsPage/AllSubjectsPage";
import CollectionPage from "./containers/CollectionPage/CollectionPage";
import ErrorPage from "./containers/ErrorPage/ErrorPage";
import ArenaAdminPage from "./containers/MyNdla/Arena/ArenaAdminPage";
import ArenaFlagPage from "./containers/MyNdla/Arena/ArenaFlagPage";
Expand Down Expand Up @@ -109,6 +110,7 @@ const AppRoutes = ({ base }: AppProps) => {
<Route path="utdanning/:programme" element={<ProgrammePage />}>
<Route path=":grade" element={null} />
</Route>
<Route path="collection/:collectionLanguage" element={<CollectionPage />} />
<Route path="podkast">
<Route index element={<PodcastSeriesListPage />} />
<Route path=":id" element={<PodcastSeriesPage />} />
Expand Down
107 changes: 15 additions & 92 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,14 +32,13 @@ import "@fontsource/source-serif-pro/700.css";
import "@fontsource/source-serif-pro/index.css";
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 { 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 { UserAgentProvider } from "./UserAgentContext";
import { createApolloClient, createApolloLinks } from "./util/apiHelpers";
import { createApolloClient } from "./util/apiHelpers";

declare global {
interface Window extends NDLAWindow {}
Expand All @@ -49,10 +48,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 @@ -62,17 +61,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 @@ -81,7 +70,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 @@ -97,82 +86,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 === config.defaultLocale && !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 @@ -194,7 +117,7 @@ renderOrHydrate(
<ApolloProvider client={client}>
<CacheProvider value={cache}>
<VersionHashProvider value={versionHash}>
<LanguageWrapper basename={basename} />
<UserAgentWrapper basename={lang} />
</VersionHashProvider>
</CacheProvider>
</ApolloProvider>
Expand Down
79 changes: 79 additions & 0 deletions src/components/Collection/CollectionContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Copyright (c) 2024-present, NDLA.
*
* This source code is licensed under the GPLv3 license found in the
* LICENSE file in the root directory of this source tree.
*
*/

import { CSSProperties, ReactNode, useMemo } from "react";
import styled from "@emotion/styled";
import { breakpoints, colors, mq, spacing } from "@ndla/core";

interface Props {
children: ReactNode;
imageUrl: string;
}

const StyledBackground = styled.div`
width: 100%;
margin: 0 auto;
background-image: var(--programme-image);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 400px;

${mq.range({ until: breakpoints.tablet })} {
height: 160px;
margin: ${spacing.normal} ${spacing.normal} 0;
width: calc(100% - ${spacing.medium});
}
${mq.range({ until: breakpoints.mobileWide })} {
height: 128px;
}
`;

const StyledOneColumn = styled.div`
display: flex;
flex-direction: column;
background: ${colors.white};
width: 90%;
margin-top: -170px;
padding: 1px ${spacing.large};
${mq.range({ until: breakpoints.tablet })} {
width: 100%;
margin: 0;
padding: 1px ${spacing.normal};
}
`;

const StyledMain = styled.main`
display: flex;
width: 100%;
flex-direction: column;
align-items: center;
`;

const ContentWrapper = styled.div`
max-width: 1105px;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
`;

const CollectionContainer = ({ children, imageUrl }: Props) => {
const style = useMemo(() => ({ "--programme-image": `url(${imageUrl}` }) as CSSProperties, [imageUrl]);

return (
<StyledMain>
<ContentWrapper>
<StyledBackground style={style} />
<StyledOneColumn>{children}</StyledOneColumn>
</ContentWrapper>
</StyledMain>
);
};

export default CollectionContainer;
3 changes: 2 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export const TOOLBOX_STUDENT_SUBJECT_ID = "urn:subject:1:54b1727c-2d91-4512-901c

export const SKIP_TO_CONTENT_ID = "SkipToContentId";
export const SUPPORTED_LANGUAGES = ["nb", "nn", "en", "se"];
export const STORED_LANGUAGE_COOKIE_KEY = "language";
export const STORED_RESOURCE_VIEW_SETTINGS = "STORED_RESOURCE_VIEW_SETTINGS";

export const PROGRAMME_PATH = "/utdanning";
Expand Down Expand Up @@ -70,3 +69,5 @@ export const programmeRedirects: Record<string, string> = {
studiespesialisering: "studiespesialisering__7d5badf01ff2",
"teknologi-og-industrifag": "teknologi-og-industrifag__a920d0b5cbbb",
};

export const COLLECTION_LANGUAGES = ["nb", "nn", "en", "se", "sma", "ukr"];
Loading
Loading