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

Adding language preferences for the UI and tasks #881

Merged
merged 3 commits into from
Jan 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion website/next-i18next.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
i18n: {
defaultLocale: "en",
locales: ["en"],
locales: ["de", "en", "fr"],
},
};
45 changes: 45 additions & 0 deletions website/package-lock.json

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

2 changes: 2 additions & 0 deletions website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@next/font": "^13.1.0",
"@prisma/client": "^4.7.1",
"@tailwindcss/forms": "^0.5.3",
"accept-language-parser": "^1.5.0",
"autoprefixer": "^10.4.13",
"axios": "^1.2.1",
"boolean": "^3.2.0",
Expand All @@ -55,6 +56,7 @@
"npm": "^9.2.0",
"postcss-focus-visible": "^7.1.0",
"react": "18.2.0",
"react-cookies": "^0.1.1",
"react-dom": "18.2.0",
"react-feature-flags": "^1.0.0",
"react-hook-form": "^7.42.1",
Expand Down
2 changes: 2 additions & 0 deletions website/src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useSession } from "next-auth/react";
import { useTranslation } from "next-i18next";
import { Flags } from "react-feature-flags";
import { FaUser } from "react-icons/fa";
import { LanguageSelector } from "src/components/LanguageSelector";

import { UserMenu } from "./UserMenu";

Expand Down Expand Up @@ -45,6 +46,7 @@ export function Header() {
<Flags authorizedFlags={["flagTest"]}>
<Text>FlagTest</Text>
</Flags>
<LanguageSelector />
<AccountButton />
<UserMenu />
</Flex>
Expand Down
40 changes: 40 additions & 0 deletions website/src/components/LanguageSelector/LanguageSelector.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Select } from "@chakra-ui/react";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
import { useCallback, useMemo } from "react";
import cookie from "react-cookies";

const LanguageSelector = () => {
const router = useRouter();
const { i18n } = useTranslation();

const { language: currentLanguage } = i18n;
const languageNames = useMemo(() => {
return new Intl.DisplayNames([currentLanguage], {
type: "language",
});
}, [currentLanguage]);

const languageChanged = useCallback(
async (option) => {
const locale = option.target.value;
cookie.save("NEXT_LOCALE", locale, { path: "/" });
const path = router.asPath;
return router.push(path, path, { locale });
},
[router]
);

const locales = router.locales;
return (
<Select onChange={languageChanged} defaultValue={currentLanguage}>
{locales.map((locale) => (
<option key={locale} value={locale}>
{languageNames.of(locale) ?? locale}
</option>
))}
</Select>
);
};

export { LanguageSelector };
1 change: 1 addition & 0 deletions website/src/components/LanguageSelector/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./LanguageSelector";
7 changes: 5 additions & 2 deletions website/src/lib/oasst_api_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,11 @@ export class OasstApiClient {
// TODO return a strongly typed Task?
// This method is used to store a task in RegisteredTask.task.
// This is a raw Json type, so we can't use it to strongly type the task.
async fetchTask(taskType: string, user: BackendUserCore): Promise<any> {
async fetchTask(taskType: string, user: BackendUserCore, lang: string): Promise<any> {
return this.post("/api/v1/tasks/", {
type: taskType,
user,
lang,
});
}

Expand All @@ -136,14 +137,16 @@ export class OasstApiClient {
messageId: string,
userMessageId: string,
content: object,
user: BackendUserCore
user: BackendUserCore,
lang: string
): Promise<any> {
return this.post("/api/v1/tasks/interaction", {
type: updateType,
user,
task_id: taskId,
message_id: messageId,
user_message_id: userMessageId,
lang,
...content,
});
}
Expand Down
28 changes: 27 additions & 1 deletion website/src/lib/users.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import parser from "accept-language-parser";
import type { NextApiRequest } from "next";
import { i18n } from "src/../next-i18next.config";
import prisma from "src/lib/prismadb";
import type { BackendUserCore } from "src/types/Users";

const LOCALE_SET = new Set(i18n.locales);

/**
* Returns the most appropriate user language using the following priority:
*
* 1. The `NEXT_LOCALE` cookie which is set by the client side and will be in
* the set of supported locales.
* 2. The `accept-language` header if it contains a supported locale as set by
* the i18n module.
* 3. "en" as a final fallback.
*/
const getUserLanguage = (req: NextApiRequest) => {
const cookieLanguage = req.cookies["NEXT_LOCALE"];
if (cookieLanguage) {
return cookieLanguage;
}
const headerLanguages = parser.parse(req.headers["accept-language"]);
if (headerLanguages.length > 0 && LOCALE_SET.has(headerLanguages[0].code)) {
return headerLanguages[0].code;
}
return "en";
};

/**
* Returns a `BackendUserCore` that can be used for interacting with the Backend service.
*
Expand Down Expand Up @@ -35,4 +61,4 @@ const getBackendUserCore = async (id: string) => {
} as BackendUserCore;
};

export { getBackendUserCore };
export { getBackendUserCore, getUserLanguage };
5 changes: 3 additions & 2 deletions website/src/pages/api/new_task/[task_type].ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { withoutRole } from "src/lib/auth";
import { oasstApiClient } from "src/lib/oasst_api_client";
import prisma from "src/lib/prismadb";
import { getBackendUserCore } from "src/lib/users";
import { getBackendUserCore, getUserLanguage } from "src/lib/users";

/**
* Returns a new task created from the Task Backend. We do a few things here:
Expand All @@ -14,11 +14,12 @@ import { getBackendUserCore } from "src/lib/users";
const handler = withoutRole("banned", async (req, res, token) => {
// Fetch the new task.
const { task_type } = req.query;
const userLanguage = getUserLanguage(req);

const user = await getBackendUserCore(token.sub);
let task;
try {
task = await oasstApiClient.fetchTask(task_type as string, user);
task = await oasstApiClient.fetchTask(task_type as string, user, userLanguage);
} catch (err) {
console.error(err);
res.status(500).json(err);
Expand Down
13 changes: 11 additions & 2 deletions website/src/pages/api/update_task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Prisma } from "@prisma/client";
import { withoutRole } from "src/lib/auth";
import { oasstApiClient } from "src/lib/oasst_api_client";
import prisma from "src/lib/prismadb";
import { getBackendUserCore } from "src/lib/users";
import { getBackendUserCore, getUserLanguage } from "src/lib/users";

/**
* Stores the task interaction with the Task Backend and then returns the next task generated.
Expand Down Expand Up @@ -41,9 +41,18 @@ const handler = withoutRole("banned", async (req, res, token) => {
});

const user = await getBackendUserCore(token.sub);
const userLanguage = getUserLanguage(req);
let newTask;
try {
newTask = await oasstApiClient.interactTask(update_type, taskId, frontendId, interaction.id, content, user);
newTask = await oasstApiClient.interactTask(
update_type,
taskId,
frontendId,
interaction.id,
content,
user,
userLanguage
);
} catch (err) {
console.error(JSON.stringify(err));
return res.status(500).json(err);
Expand Down