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

Add internationalization (i18n) support with react-i18next #58

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
135 changes: 134 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,14 @@
"@fortawesome/free-solid-svg-icons": "^6.6.0",
"@fortawesome/react-fontawesome": "^0.2.2",
"@monaco-editor/react": "^4.6.0",
"i18next": "^24.1.0",
"i18next-browser-languagedetector": "^8.0.2",
"i18next-http-backend": "^3.0.1",
"monaco-editor": "^0.52.0",
"purecss": "^3.0.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-i18next": "^15.1.4",
"sweetalert2": "<=11.4.8",
"sweetalert2-react-content": "^5.0.7",
"tshet-uinh": "^0.15.0",
Expand Down
10 changes: 10 additions & 0 deletions public/locales/en/translation.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"schemaCompareDifferent": "Found {{count}} different items.",
"phonologicalPosition": "Phonological Position",
"representativeCharacter": "Representative Character",
"schemaCompareSame": "The results of the program derivation are the same.",
"copyToClipboard": "Copy to clipboard",
"copySuccess": "Successfully copied to clipboard",
"copyFailed": "Unable to copy to clipboard",
"tshetUinhAutoderiver": "Tshet-uinh Autoderiver"
}
10 changes: 10 additions & 0 deletions public/locales/zh/translation.json
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Members and I will need to decide on how the messages should be organised into groups

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@syimyuzya @untunt @ayaka14732 Perhaps let’s have a meeting soon?

Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"schemaCompareDifferent": "找到 {{count}} 個相異項目。",
"phonologicalPosition": "音韻地位",
"representativeCharacter": "代表字",
"schemaCompareSame": "方案推導結果相同。",
"copyToClipboard": "複製到剪貼簿",
"copySuccess": "成功複製到剪貼簿",
"copyFailed": "無法複製到剪貼簿",
"tshetUinhAutoderiver": "切韻音系自動推導器"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be at the top of the file

}
18 changes: 16 additions & 2 deletions src/Components/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useRef } from "react";
import { useCallback, useEffect, useRef } from "react";

import "purecss/build/pure.css";
// NOTE sweetalert2's ESM export does not setup styles properly, manually importing
Expand All @@ -12,6 +12,9 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Main from "./Main";
import Swal from "../Classes/SwalReact";
import { codeFontFamily, noop } from "../consts";
import { useTranslation } from "react-i18next";

import i18n from "../i18n";

injectGlobal`
html,
Expand Down Expand Up @@ -565,14 +568,25 @@ const FontPreload = styled.span`
`;

export default function App() {
const { t } = useTranslation();
const evaluateHandlerRef = useRef(noop);

useEffect(() => {
document.documentElement.lang = i18n.language;
i18n.on("languageChanged", lng => {
document.documentElement.lang = lng;
});

document.title = t("tshetUinhAutoderiver");
Comment on lines +575 to +580
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be put into i18n.ts since nothing is related to the App component.

Suggested change
document.documentElement.lang = i18n.language;
i18n.on("languageChanged", lng => {
document.documentElement.lang = lng;
});
document.title = t("tshetUinhAutoderiver");
document.documentElement.lang = i18n.language;
document.title = i18n.t("tshetUinhAutoderiver");
i18n.on("languageChanged", lng => {
document.documentElement.lang = lng;
document.title = i18n.t("tshetUinhAutoderiver");
});

}, []);

return (
<Container>
<Content>
<header>
<nav>
<Heading>
<Title>切韻音系自動推導器</Title>
<Title>{t("tshetUinhAutoderiver")}</Title>
<Version>v{__APP_VERSION__}</Version>
<LinkToLegacy>
<a href="//nk2028.shn.hk/qieyun-autoderiver-legacy/">
Expand Down
11 changes: 7 additions & 4 deletions src/Components/Main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import styled from "@emotion/styled";
import { faCopy } from "@fortawesome/free-regular-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

import { useTranslation } from "react-i18next";

import SchemaEditor from "./SchemaEditor";
import Spinner from "./Spinner";
import { listenTooltip } from "./TooltipChar";
Expand Down Expand Up @@ -142,6 +144,7 @@ const Loading = styled.div`
let evaluationResult: ReactNode = [];

export default function Main({ evaluateHandlerRef }: { evaluateHandlerRef: MutableRefObject<() => void> }) {
const { t } = useTranslation();
const [state, setState] = useState(initialState);
const { article, option, convertVariant, syncCharPosition } = state;
useEffect(() => {
Expand Down Expand Up @@ -181,19 +184,19 @@ export default function Main({ evaluateHandlerRef }: { evaluateHandlerRef: Mutab

const [loading, setLoading] = useState(false);

const [copyTooltipText, setCopyTooltipText] = useState("複製到剪貼簿");
const [copyTooltipText, setCopyTooltipText] = useState(t("copyToClipboard"));
const copyEvaluationResult = useCallback(async () => {
const content = ref.current.textContent?.trim();
if (content) {
try {
await navigator.clipboard.writeText(content);
setCopyTooltipText("成功複製到剪貼簿");
setCopyTooltipText(t("copySuccess"));
} catch {
setCopyTooltipText("無法複製到剪貼簿");
setCopyTooltipText(t("copyFailed"));
}
}
}, []);
const onHideTooltip = useCallback(() => setCopyTooltipText("複製到剪貼簿"), []);
const onHideTooltip = useCallback(() => setCopyTooltipText(t("copyToClipboard")), []);
Comment on lines 198 to +199
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

t will be a dependency in these cases


// XXX Please Rewrite
useEffect(() => {
Expand Down
22 changes: 22 additions & 0 deletions src/i18n.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";

import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";

i18n
.use(Backend)
// detect user language
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove this line since it’s self-explanatory

.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "zh",
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
backend: {
loadPath: "/tshet-uinh-autoderiver/locales/{{lng}}/translation.json",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will need to follow assetLocation in vite.config.ts since we also have vite.cos.config.ts for production

},
});

export default i18n;
2 changes: 2 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { createRoot } from "react-dom/client";

import App from "./Components/App";

import "./i18n";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unnecessary, i18n.ts would have already been imported in App.ts


const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
Expand Down
12 changes: 8 additions & 4 deletions src/options.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import Table from "./Components/Table";
import TooltipChar from "./Components/TooltipChar";
import { noop } from "./consts";

import i18n from "./i18n";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be at least one empty line between import groups - eslint(import/order)
This line should be in the previous group

import type { CustomNode } from "./Classes/CustomElement";
import type { Entry, MainState, Option, SchemaState, ReactNode } from "./consts";
import type { Entry, MainState, Option, ReactNode, SchemaState } from "./consts";

const Title = styled.h3`
padding: 0 0 1rem 0.25rem;
Expand Down Expand Up @@ -204,13 +205,16 @@ export const evaluateOption: Record<Option, Handler> = {
return result.length ? (
<>
<Title>
找到 {result.length} 個相異項目。
{i18n.t("schemaCompareDifferent", { count: result.length })}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is tricky, we will need a functional component like

function Translation({ message, ...options }) {
  const { t } = useTranslation();
  return t(message, options);
}

to get the messages sync with the language chosen (I am new to the i18next library and I haven’t think of how to type the component correctly yet, but I believe this should be what react-i18next provide. I wonder if there are alternative i18n libraries that provide such components.)

<span hidden>{"\n\n"}</span>
</Title>
<Table head={["音韻地位", ...title(schemas), "代表字"]} body={finalize(result)} />
<Table
head={[i18n.t("phonologicalPosition"), ...title(schemas), i18n.t("representativeCharacter")]}
body={finalize(result)}
/>
</>
) : (
<h3>方案推導結果相同。</h3>
<h3>{i18n.t("schemaCompareSame")}</h3>
);
},
};