(react) expose currentLocale in CunninghamContext

Expose `currentLocale` value to let know its subscribers
what is the locale value currently in use.
This commit is contained in:
Lebaud Antoine
2023-06-26 18:55:13 +02:00
committed by aleb_the_flash
parent 3b13bcae65
commit f03ef6a9e1
2 changed files with 56 additions and 6 deletions

View File

@@ -1,7 +1,12 @@
import { render, screen } from "@testing-library/react";
import React, { PropsWithChildren, useMemo, useState } from "react";
import userEvent from "@testing-library/user-event";
import { CunninghamProvider, useCunningham } from ":/components/Provider/index";
import { expect } from "vitest";
import {
CunninghamProvider,
DEFAULT_LOCALE,
useCunningham,
} from ":/components/Provider/index";
import * as enUS from ":/locales/en-US.json";
import { Button } from ":/components/Button";
@@ -102,4 +107,50 @@ describe("<CunninghamProvider />", () => {
name: "components.will_never_exist",
});
});
it("should return current locale", () => {
const locale = "fr-FR";
const Wrapper = (props: PropsWithChildren) => {
return (
<CunninghamProvider currentLocale={locale}>
{props.children}
</CunninghamProvider>
);
};
const Wrapped = () => {
const { currentLocale } = useCunningham();
expect(currentLocale).eq(locale);
return <div />;
};
render(<Wrapped />, { wrapper: Wrapper });
});
it("should return default locale if no current locale is provided", () => {
const Wrapper = (props: PropsWithChildren) => {
return <CunninghamProvider>{props.children}</CunninghamProvider>;
};
const Wrapped = () => {
const { currentLocale } = useCunningham();
expect(currentLocale).eq(DEFAULT_LOCALE);
return <div />;
};
render(<Wrapped />, { wrapper: Wrapper });
});
it("should return default locale if the current locale is not supported", () => {
const wrongLocale = "fr_FR";
const Wrapper = (props: PropsWithChildren) => {
return (
<CunninghamProvider currentLocale={wrongLocale}>
{props.children}
</CunninghamProvider>
);
};
const Wrapped = () => {
const { currentLocale } = useCunningham();
expect(currentLocale).eq(DEFAULT_LOCALE);
return <div />;
};
render(<Wrapped />, { wrapper: Wrapper });
});
});

View File

@@ -15,6 +15,7 @@ const CunninghamContext = createContext<
| undefined
| {
t: (key: string, vars?: Record<string, string | number>) => string;
currentLocale: string;
}
>(undefined);
@@ -57,17 +58,14 @@ export const CunninghamProvider = ({
);
const locale = useMemo(() => {
if (!locales[currentLocale]) {
return locales[DEFAULT_LOCALE];
}
return locales[currentLocale];
return (locales[currentLocale] && currentLocale) || DEFAULT_LOCALE;
}, [currentLocale, locales]);
const context = useMemo(
() => ({
t: (key: string, vars?: Record<string, string | number>) => {
let message: string =
findTranslation(key, locale) ??
findTranslation(key, locales[locale]) ??
findTranslation(key, locales[DEFAULT_LOCALE]) ??
key;
@@ -80,6 +78,7 @@ export const CunninghamProvider = ({
return message;
},
currentLocale: locale,
}),
[currentLocale, locales]
);