Skip to content

Commit

Permalink
Merge pull request #84 from vordgi/nt-83
Browse files Browse the repository at this point in the history
nt-83 getLanguage configuration option instead of server context
  • Loading branch information
vordgi authored May 6, 2024
2 parents b42354e + 21ca57d commit 8a821e8
Show file tree
Hide file tree
Showing 15 changed files with 131 additions and 173 deletions.
11 changes: 1 addition & 10 deletions package/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,9 @@
"./ClientTranslation": {
"default": "./dist/ClientTranslation.js"
},
"./createTranslation": {
"default": "./dist/createTranslation.js"
},
"./getTranslation": {
"default": "./dist/getTranslation.js"
},
"./I18nProvider": {
"default": "./dist/I18nProvider.js"
},
"./I18nTransmitter": {
"default": "./dist/I18nTransmitter.js"
},
Expand All @@ -26,9 +20,6 @@
},
"./useTranslation": {
"default": "./dist/useTranslation.js"
},
"./withI18n": {
"default": "./dist/withI18n.js"
}
},
"files": [
Expand Down Expand Up @@ -70,8 +61,8 @@
"react": ">= 18.2.0"
},
"dependencies": {
"html-entities": "2.4.0",
"@nimpl/getters": "1.3.4",
"html-entities": "2.4.0",
"object-path": "0.11.8"
}
}
21 changes: 0 additions & 21 deletions package/src/I18nProvider.tsx

This file was deleted.

26 changes: 15 additions & 11 deletions package/src/I18nTransmitter.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import React from "react";
import op from "object-path";
import getServerContext from "@nimpl/getters/get-server-context";
import { I18nContext } from "./lib/I18nContext";
import { type I18nOptions, type Translates } from "./types";
import ClientI18nProvider from "./lib/ClientI18nProvider";
import formatServerTranslate from "./lib/formatServerTranslate";
import getDictionary from "./lib/getDictionary";
import loadI18nData from "./lib/loadI18nData";

export type I18nTransmitterProps = {
terms: (string | [string, I18nOptions])[];
children: React.ReactNode;
cleanThread?: boolean;
language?: string;
};

type ClientTranslates = { [key: string]: string };
Expand All @@ -33,16 +32,21 @@ const formatServerTranslates = (
}
};

const I18nTransmitter: React.FC<I18nTransmitterProps> = async ({ terms, children, cleanThread }) => {
const context = getServerContext(I18nContext);
const I18nTransmitter: React.FC<I18nTransmitterProps> = async ({
language: argLanguage,
terms,
children,
cleanThread,
}) => {
const { dictionary, language: configLanguage } = await loadI18nData();
const language = argLanguage || configLanguage;

if (!context) {
throw new Error("Please, Init I18nProvider - https://github.com/vordgi/nimpl-i18n#server-components");
if (!language) {
throw new Error(
"Unable to get the language in the createTranslation function. Please check the getLanguage method in the configuration file or pass the language as an argument.",
);
}

const { lang } = context;
const dictionary = await getDictionary(lang);

const result: { [key: string]: string } = {};
terms.forEach((term) => {
if (Array.isArray(term)) {
Expand All @@ -56,7 +60,7 @@ const I18nTransmitter: React.FC<I18nTransmitterProps> = async ({ terms, children
});

return (
<ClientI18nProvider lang={lang} translates={result} cleanThread={cleanThread}>
<ClientI18nProvider language={language} translates={result} cleanThread={cleanThread}>
{children}
</ClientI18nProvider>
);
Expand Down
4 changes: 3 additions & 1 deletion package/src/ServerTranslation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ type ServerTranslationProps = {
components?: { [key: string]: JSX.Element };
query?: I18nOptions["query"];
removeUnusedQueries?: I18nOptions["removeUnusedQueries"];
language?: string;
};

const ServerTranslation: React.FC<ServerTranslationProps> = async ({
term,
components,
query,
removeUnusedQueries,
language,
}) => {
const { t } = await getTranslation();
const { t } = await getTranslation({ language });
const text = t(term, { query, removeUnusedQueries });

return <Translation term={term} text={text} components={components} />;
Expand Down
12 changes: 9 additions & 3 deletions package/src/configuration/getConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const getConfig = async (): Promise<Config> => {
try {
if (fs.existsSync(CONFIG_PATH)) {
const config: { default: Config } = await dynamicImport(pathToFileURL(CONFIG_PATH).href);
const { load, languages } = config.default;
const { load, getLanguage, languages } = config.default;

if (!load) {
throw new Error(
Expand All @@ -25,10 +25,16 @@ const getConfig = async (): Promise<Config> => {
);
}

if (!getLanguage) {
throw new Error(
`Can't find getLanguage method in configuration file - https://github.com/vordgi/nimpl-i18n#configuration`,
);
}

return config.default;
}
} catch {
//
} catch (err) {
console.error(err);
}
throw new Error("Can't load config - https://github.com/vordgi/nimpl-i18n#configuration");
};
Expand Down
1 change: 1 addition & 0 deletions package/src/configuration/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ export type Meta = { lastUpdated: number; isRevalidated?: boolean } & Record<str

export type Config = {
load(key: string, meta?: Meta): Promise<{ data: unknown; meta: Meta }>;
getLanguage(options: { pathname: string | null; params: { [key: string]: string | string[] } }): Promise<string>;
languages: string[];
};
33 changes: 0 additions & 33 deletions package/src/createTranslation.ts

This file was deleted.

32 changes: 17 additions & 15 deletions package/src/getTranslation.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import op from "object-path";
import getServerContext from "@nimpl/getters/get-server-context";
import { I18nContext } from "./lib/I18nContext";
import formatServerTranslate from "./lib/formatServerTranslate";
import { type I18nOptions } from "./types";
import getDictionary from "./lib/getDictionary";

type GetTranslationReturnType = { t: (term: string, opts?: I18nOptions) => string; lang: string };

const getTranslation = async (namespace?: string): Promise<GetTranslationReturnType> => {
const context = getServerContext(I18nContext);

if (!context) {
throw new Error("Please, Init I18nProvider - https://nimpl.tech/i18n/usage#i18nprovider");
import loadI18nData from "./lib/loadI18nData";

type GetTranslationReturnType = { t: (term: string, opts?: I18nOptions) => string; language: string };

const getTranslation = async (options?: {
language?: string;
namespace?: string;
}): Promise<GetTranslationReturnType> => {
const { language: argLanguage, namespace } = options || {};
const { dictionary, language: configLanguage } = await loadI18nData();
const language = argLanguage || configLanguage;

if (!language) {
throw new Error(
"Unable to get the language in the createTranslation function. Please check the getLanguage method in the configuration file or pass the language as an argument.",
);
}

const dictionary = await getDictionary(context.lang);
const { lang } = context;

const namespaceDictionary = namespace ? op.get(dictionary, namespace) : dictionary;

const t: GetTranslationReturnType["t"] = (term, opts) => {
Expand All @@ -37,7 +39,7 @@ const getTranslation = async (namespace?: string): Promise<GetTranslationReturnT
return formatServerTranslate({ term: fullTerm, text: translation, parseEntities: true, ...opts });
};

return { t, lang };
return { t, language };
};

export default getTranslation;
2 changes: 1 addition & 1 deletion package/src/lib/ClientI18nContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

import { createContext } from "react";

type ClientI18nContextType = { lang: string; translates: { [key: string]: string } } | null;
type ClientI18nContextType = { language: string; translates: { [key: string]: string } } | null;

export const ClientI18nContext = createContext<ClientI18nContextType>(null);
6 changes: 3 additions & 3 deletions package/src/lib/ClientI18nProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ import { ClientI18nContext } from "./ClientI18nContext";

type ClientI18nProviderProps = {
translates: { [key: string]: string };
lang: string;
language: string;
children: React.ReactNode;
cleanThread?: boolean;
};

const ClientI18nProvider: React.FC<ClientI18nProviderProps> = ({ translates, children, lang, cleanThread }) => {
const ClientI18nProvider: React.FC<ClientI18nProviderProps> = ({ translates, children, language, cleanThread }) => {
const prevTranslates = useContext(ClientI18nContext);

if (cleanThread) {
Object.assign(translates, prevTranslates?.translates);
}

return <ClientI18nContext.Provider value={{ lang, translates }}>{children}</ClientI18nContext.Provider>;
return <ClientI18nContext.Provider value={{ language, translates }}>{children}</ClientI18nContext.Provider>;
};

export default ClientI18nProvider;
7 changes: 0 additions & 7 deletions package/src/lib/I18nContext.tsx

This file was deleted.

15 changes: 0 additions & 15 deletions package/src/lib/getDictionary.ts

This file was deleted.

20 changes: 20 additions & 0 deletions package/src/lib/loadI18nData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import getConfig from "../configuration/getConfig";
import { type Translates } from "../types";
import { getPathname } from "@nimpl/getters/get-pathname";
import { getParams } from "@nimpl/getters/get-params";

const loadI18nData = async (): Promise<{ dictionary: Translates; language: string }> => {
const config = await getConfig();
const language = await config.getLanguage({ pathname: getPathname(), params: getParams() });

if (!language || !config.languages.includes(language)) {
throw new Error(
`Can\' load data for language "${language}", valid languages are: ${config.languages.join(", ")}`,
);
}

const { data } = await config.load(language);
return { dictionary: data as Translates, language };
};

export default loadI18nData;
8 changes: 4 additions & 4 deletions package/src/useTranslation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { type I18nOptions } from "./types";
import { ClientI18nContext } from "./lib/ClientI18nContext";
import injectQuery from "./lib/injectQuery";

type GetTranslationReturnType = { t: (term: string, opts?: I18nOptions) => string; lang: string };
type GetTranslationReturnType = { t: (term: string, opts?: I18nOptions) => string; language: string };

const useTranslation = (namespace?: string): GetTranslationReturnType => {
const useTranslation = ({ namespace }: { namespace?: string } = {}): GetTranslationReturnType => {
const context = useContext(ClientI18nContext);

if (!context) {
Expand All @@ -14,7 +14,7 @@ const useTranslation = (namespace?: string): GetTranslationReturnType => {
);
}

const { lang, translates } = context;
const { language, translates } = context;

const t: GetTranslationReturnType["t"] = (term, opts) => {
let termKey: string;
Expand All @@ -39,7 +39,7 @@ const useTranslation = (namespace?: string): GetTranslationReturnType => {
return translation;
};

return { t, lang };
return { t, language };
};

export default useTranslation;
Loading

0 comments on commit 8a821e8

Please sign in to comment.