Skip to content

Commit

Permalink
🦄 refactor(intl): server intl
Browse files Browse the repository at this point in the history
  • Loading branch information
summerscar committed Nov 23, 2024
1 parent bd08252 commit 4a172d7
Show file tree
Hide file tree
Showing 14 changed files with 42 additions and 57 deletions.
6 changes: 3 additions & 3 deletions app/(home)/account/page.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { getAllDicts } from "@/actions/user-dict-action";
import { filterAndSortDictList } from "@/actions/user-dict-utils";
import InfoIcon from "@/assets/svg/info.svg";
import { getServerI18n } from "@/utils/i18n";
import { auth } from "auth";
import { getTranslations } from "next-intl/server";
import Link from "next/link";
import { WordLists } from "./_components/lists";

export const generateMetadata = async () => {
const tAccount = await getServerI18n("Account");
const tAccount = await getTranslations("Account");

return {
title: tAccount("profile"),
Expand All @@ -17,7 +17,7 @@ export const generateMetadata = async () => {
const AccountPage = async () => {
const session = await auth();
const dicts = filterAndSortDictList(await getAllDicts(), session, false);
const tAccount = await getServerI18n("Account");
const tAccount = await getTranslations("Account");

if (!session) {
return (
Expand Down
4 changes: 2 additions & 2 deletions app/(home)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Footer } from "@/components/footer";
import { Header } from "@/components/header";
import { DefaultLayout } from "@/components/root-layout";
import { getServerI18n } from "@/utils/i18n";
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";

export async function generateMetadata(): Promise<Metadata> {
const t = await getServerI18n("Index");
const t = await getTranslations("Index");
return {
title: t("title"),
description: t("description"),
Expand Down
4 changes: 2 additions & 2 deletions app/(home)/learn/[level]/[...doc_path]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import NextIcon from "@/assets/svg/next.svg";
import PrevIcon from "@/assets/svg/prev.svg";
import { type DocPathParams, Levels } from "@/types";
import { getServerI18n } from "@/utils/i18n";
import { isDev } from "@/utils/is-dev";
import { type FileItem, listAllDocs } from "@/utils/list-docs";
import { loadMDX } from "@/utils/load-mdx";
import { timeOut } from "@/utils/time-out";
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import Link from "next/link";
import { redirect } from "next/navigation";
import { MDContentWrapper } from "../_components/markdown-wrapper";
Expand All @@ -16,7 +16,7 @@ export async function generateMetadata(props: {
params: Promise<DocPathParams>;
}): Promise<Metadata> {
const params = await props.params;
const t = await getServerI18n("Header");
const t = await getTranslations("Header");
const level = params.level;

if (!params.doc_path.length) return { title: t(level) };
Expand Down
4 changes: 2 additions & 2 deletions app/(home)/learn/[level]/_components/category.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import MenuIcon from "@/assets/svg/menu.svg";
import type { DocPathParams } from "@/types";
import { getServerI18n } from "@/utils/i18n";
import { type FileItem, type SubDirItem, listAllDocs } from "@/utils/list-docs";
import { getTranslations } from "next-intl/server";
import {
CategoryActiveClient,
MobileCategoryHeader,
Expand All @@ -10,7 +10,7 @@ import { CategoryParentClient } from "./category-parent-client";

const DocsCategory = async ({ level }: Pick<DocPathParams, "level">) => {
const docs = await listAllDocs(level);
const t = await getServerI18n("Header");
const t = await getTranslations("Header");

const buildTree = (docs: (FileItem | SubDirItem)[], path: string[] = []) => {
return docs.map((doc) => {
Expand Down
1 change: 0 additions & 1 deletion app/(home)/learn/[level]/_components/markdown-wrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"use client";
import { useSelectToSearch } from "@/hooks/use-select-to-search";
import { useLocale } from "next-intl";
import { usePathname } from "next/navigation";
import {
type ReactNode,
Expand Down
8 changes: 4 additions & 4 deletions app/(home)/tools/[[...tool]]/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type ToolName, toolsNames } from "@/types/tools";
import { getServerI18n } from "@/utils/i18n";
import clsx from "clsx";
import { getTranslations } from "next-intl/server";
import Link from "next/link";

const list: {
Expand Down Expand Up @@ -38,8 +38,8 @@ const list: {
export async function generateMetadata(props: {
params: Promise<{ tool: string[] }>;
}) {
const tHeader = await getServerI18n("Header");
const tTools = await getServerI18n("Tools");
const tHeader = await getTranslations("Header");
const tTools = await getTranslations("Tools");
const tool = ((await props.params).tool || [])[0] as ToolName;
return {
title: tool
Expand Down Expand Up @@ -74,7 +74,7 @@ export default async function Layout({
children,
params,
}: { children: React.ReactNode; params: Promise<{ tool: string[] }> }) {
const tTools = await getServerI18n("Tools");
const tTools = await getTranslations("Tools");
const tool = ((await params).tool || [])[0] as ToolName;

return (
Expand Down
4 changes: 2 additions & 2 deletions app/(home)/topik/[level]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { keystoneContext } from "@/../keystone/context";
import { TopikLevels } from "@/types";
import { getServerI18n } from "@/utils/i18n";
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { unstable_cache } from "next/cache";
import Link from "next/link";
import type { TopikLevelType } from ".keystone/types";
Expand All @@ -10,7 +10,7 @@ export async function generateMetadata(props: {
params: Promise<{ level: TopikLevelType }>;
}): Promise<Metadata> {
const params = await props.params;
const tIndex = await getServerI18n("Index");
const tIndex = await getTranslations("Index");
return {
title: `${tIndex("title")}-${TopikLevels[params.level]}`,
};
Expand Down
4 changes: 2 additions & 2 deletions app/(home)/topik/page.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { keystoneContext } from "@/../keystone/context";
import { TopikLevels } from "@/types";
import { getServerI18n } from "@/utils/i18n";
import type { Metadata } from "next";
import { getTranslations } from "next-intl/server";
import { unstable_cache } from "next/cache";
import Link from "next/link";
import type { TopikLevelType } from ".keystone/types";

export async function generateMetadata(): Promise<Metadata> {
const tIndex = await getServerI18n("Index");
const tIndex = await getTranslations("Index");
return {
title: `${tIndex("title")}-TOPIK`,
};
Expand Down
25 changes: 7 additions & 18 deletions app/api/dict-items/create/route.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
import { addWordsToUserDictAction } from "@/actions/user-dict-action";
import { DEFAULT_SITE_LANGUAGE } from "@/utils/config";
import { sendNotificationToUser } from "@/utils/push-notification";

const getMessages = async (locale: string) => {
try {
return (await import(`../../../../messages/${locale}.json`)).default;
} catch (e) {
console.warn(`[getMessages] Fallback to ${DEFAULT_SITE_LANGUAGE}:`, e);
return (await import(`../../../../messages/${DEFAULT_SITE_LANGUAGE}.json`))
.default;
}
};
import { getTranslations } from "next-intl/server";

const POST = async (request: Request) => {
try {
Expand All @@ -25,9 +16,10 @@ const POST = async (request: Request) => {
if (!dictId || !Array.isArray(words) || !userId) {
return new Response("Body is invalid", { status: 500 });
}

const messages = await getMessages(locale);

const tNotification = await getTranslations({
locale,
namespace: "Notification",
});
await addWordsToUserDictAction(dictId, words, userId);
console.log(
"[POST][/api/dict-items/create]:",
Expand All @@ -37,11 +29,8 @@ const POST = async (request: Request) => {
// 发送通知
const notificationResult = await sendNotificationToUser(
{
title: messages.Notification.addWordSuccess,
body: messages.Notification.addWordContent.replace(
"{word}",
words.join(", "),
),
title: tNotification("addWordSuccess"),
body: tNotification("addWordContent", { word: words.join(", ") }),
data: {
url: `/?dict=${dictId}`,
dictId,
Expand Down
4 changes: 2 additions & 2 deletions app/api/og/route.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getServerI18n } from "@/utils/i18n";
import { getTranslations } from "next-intl/server";
import { ImageResponse } from "next/og";
import type { NextRequest } from "next/server";

Expand All @@ -7,7 +7,7 @@ export const runtime = "edge";
// TODO: og-image
export async function GET(req: NextRequest): Promise<Response | ImageResponse> {
try {
const t = await getServerI18n("Index");
const t = await getTranslations("Index");

const { searchParams } = new URL(req.url);
// TODO: 设备主题设置
Expand Down
8 changes: 5 additions & 3 deletions app/components/header/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import HomeIcon from "@/assets/svg/home.svg";
import { isAdminBySession } from "@/hooks/use-user";
import { getServerI18n } from "@/utils/i18n";
import { auth } from "auth";
import clsx from "clsx";
import { getTranslations } from "next-intl/server";
import Link from "next/link";
import { ActiveLinks } from "./_component/active-links";
import { CheckClientSession } from "./_component/check-client-session";
Expand All @@ -11,7 +11,9 @@ import { MobileMenu } from "./_component/mobile-menu";
import { Progress } from "./_component/progress";
import { Search } from "./_component/search";

export const headerConfig = (t: Awaited<ReturnType<typeof getServerI18n>>) => [
export const headerConfig = (
t: Awaited<ReturnType<typeof getTranslations<"Header">>>,
) => [
{
href: "/learn/beginner",
label: `${t("beginner")}`,
Expand All @@ -32,7 +34,7 @@ export const headerConfig = (t: Awaited<ReturnType<typeof getServerI18n>>) => [

const Header = async () => {
const session = await auth();
const t = await getServerI18n("Header");
const t = await getTranslations("Header");

return (
<header className="before-backdrop-shadow sticky top-0 h-[--header-height] flex border-b border-slate-900/10 w-full select-none bg-slate-300/10 text-base-content z-20 before:">
Expand Down
8 changes: 7 additions & 1 deletion app/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ import { getI18nFromCookie } from "./actions/check-i18n";
import { SITES_LANGUAGE } from "./types/site";
import { DEFAULT_SITE_LANGUAGE } from "./utils/config";

export default getRequestConfig(async () => {
export default getRequestConfig(async (request) => {
const requestLocale = await request.requestLocale;
const isRequestedLocaleSupported =
requestLocale &&
Object.values(SITES_LANGUAGE).includes(requestLocale as SITES_LANGUAGE);

const locale =
(isRequestedLocaleSupported && requestLocale) ||
(await getI18nFromCookie()) ||
(await getLanguageFromHeader()) ||
DEFAULT_SITE_LANGUAGE;
Expand Down
11 changes: 0 additions & 11 deletions app/utils/i18n.ts

This file was deleted.

8 changes: 4 additions & 4 deletions scripts/tampermonkey-create-word-from-papago.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const style = {
return;
}
const text = getWord(e.target);
toast("Word creating", "info");
toast("Word creating", "info");
e.target.textContent = "⏳";
e.target.disabled = true;
try {
Expand All @@ -109,10 +109,10 @@ const style = {
throw new Error((await res.text()) || res.statusText);
}
e.target.textContent = "✅";
toast("Word created", "success");
toast("Word created", "success");
} catch (error) {
e.target.textContent = "❌";
toast(error.message, "error");
toast(`⚠️ ${error.message}`, "error");
console.error("[dict-items/create][error]:", error);
} finally {
setTimeout(() => {
Expand Down Expand Up @@ -170,7 +170,7 @@ const toast = (message, type = "info") => {
zIndex: "9999",
backgroundColor:
type === "success"
? "green"
? "#21dc6d"
: type === "error"
? "red"
: type === "info"
Expand Down

0 comments on commit 4a172d7

Please sign in to comment.