Skip to content

Commit

Permalink
feat: finish trans
Browse files Browse the repository at this point in the history
  • Loading branch information
521xueweihan committed Aug 7, 2024
1 parent af363e2 commit bf048f9
Show file tree
Hide file tree
Showing 17 changed files with 102 additions and 53 deletions.
2 changes: 1 addition & 1 deletion next-i18next.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//next-i18next.config.js

module.exports = {
debug: true,
// debug: true,
i18n: {
defaultLocale: 'zh',
locales: ['zh', 'en'],
Expand Down
4 changes: 2 additions & 2 deletions public/locales/en/article.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
"hot": "Popular",
"last": "Latest"
},
"author": "Author: {{name}}",
"read": "Read: {{num}}"
"author": "Author {{name}}",
"read": "Views {{num}}"
}
4 changes: 2 additions & 2 deletions public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"rank": "Ranking",
"article": "Articles",
"submit": "Submit",
"profile": "My Profile",
"notification": "Notifications",
"profile": "Profile",
"notification": "Notification",
"logout": "Logout"
},
"login": {
Expand Down
2 changes: 1 addition & 1 deletion public/locales/en/rank.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"rating": "Score",
"change": "Change",
"md_change": "📊",
"model": "Type"
"model": "Model"
}
},
"netcraft": {
Expand Down
4 changes: 2 additions & 2 deletions public/locales/en/repository.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@
"title": "Comments",
"sort_hot": "Popular",
"sort_new": "Newest",
"total": "{{total}} selected comments",
"total": "{{total}} comments",
"more_reply": "View all {{total}} replies",
"load_more": "Load more...",
"no_comment": "No selected comments yet",
"no_comment": "No comments yet",
"used": "Used",
"unused": "Not Used",
"score": "Rating:",
Expand Down
8 changes: 3 additions & 5 deletions src/components/buttons/LanguageSwitcher.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// components/LanguageSwitcher.tsx
import { useRouter } from 'next/router';
import { useEffect, useRef, useState } from 'react';
import { MdTranslate } from 'react-icons/md';

type LanguageSwitchProps = {
type?: string;
Expand All @@ -9,29 +10,25 @@ type LanguageSwitchProps = {
const LanguageSwitcher = (props: LanguageSwitchProps) => {
const router = useRouter();
const { locale, asPath } = router;
const [selectedLocale, setSelectedLocale] = useState(locale);
const [isHovered, setIsHovered] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);

useEffect(() => {
const storedLocale = localStorage.getItem('locale');
if (storedLocale) {
setSelectedLocale(storedLocale);
router.push(asPath, asPath, { locale: storedLocale });
} else {
const systemLocale = navigator.language.toLowerCase().startsWith('zh')
? 'zh'
: 'en';
setSelectedLocale(systemLocale);
localStorage.setItem('locale', systemLocale);
router.push(asPath, asPath, { locale: systemLocale });
}
}, []);

const changeLanguage = (language: string) => {
localStorage.setItem('locale', language);
setSelectedLocale(language);
setIsHovered(false);
router.push(asPath, asPath, { locale: language });
};
Expand Down Expand Up @@ -74,7 +71,8 @@ const LanguageSwitcher = (props: LanguageSwitchProps) => {
aria-haspopup='true'
aria-expanded={isHovered ? 'true' : 'false'}
>
{selectedLocale === 'zh' ? '中文' : 'EN'}
<MdTranslate size={16} />
{/* {selectedLocale === 'zh' ? '中文' : 'EN'} */}
</button>
</div>

Expand Down
4 changes: 2 additions & 2 deletions src/components/buttons/ThemeSwitcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ const ThemeSwitcher: React.FC<ThemeSwitchProps> = (props: ThemeSwitchProps) => {
<button
type='button'
onClick={onToggle}
className='rounded-md p-2 transition-colors hover:bg-gray-200 dark:hover:bg-gray-700'
className='h-8 items-center justify-center rounded-md border border-gray-300 bg-white px-2 text-sm font-medium text-gray-700 shadow-sm transition-colors duration-200 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-700'
aria-label='Toggle theme'
>
{theme == 'light' ? (
{theme == 'dark' ? (
<svg
className='h-4 w-4'
data-testid='geist-icon'
Expand Down
2 changes: 1 addition & 1 deletion src/components/layout/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ const Header = () => {
{t('header.submit')}
</button>
</RepoModal>
<LanguageSwitcher />
<ThemeSwitcher />
<LanguageSwitcher />
</div>
</nav>
</div>
Expand Down
8 changes: 7 additions & 1 deletion src/components/periodical/item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,13 @@ const PeriodItem: NextPage<PeriodicalItemProps> = ({ item, index }) => {
</div>

{/* markdown 内容渲染 */}
<MDRender className='markdown-body'>{item.description}</MDRender>
<MDRender className='markdown-body'>
{i18n.language == 'en'
? item.description_en
? item.description_en
: item.description
: item.description}
</MDRender>
{/* 图片预览 */}
{item.image_url && (
<div className='my-2 flex justify-center'>
Expand Down
2 changes: 1 addition & 1 deletion src/components/respository/Info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ const Info = ({ repo, t, i18n_lang }: RepositoryProps) => {
href={repo.url}
onClick={() => handleClickLink('source', repo.rid)}
>
<h1 className='max-w-[400px] truncate text-ellipsis text-3xl font-semibold'>
<h1 className='max-w-[320px] truncate text-ellipsis text-3xl font-semibold'>
{repo.full_name.length >= 20 ? repo.name : repo.full_name}
</h1>
</CustomLink>
Expand Down
41 changes: 29 additions & 12 deletions src/components/side/Ad.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { AdvertItem } from '@/types/home';

const ImageURL =
'https://img.hellogithub.com/article/HwsoJXEiYdPhjLa_1720773908.png';
const PayURL = 'https://buymeacoffee.com/hellogithub';

interface Props {
data: AdvertItem;
Expand Down Expand Up @@ -118,19 +119,35 @@ export default function Ad({ data, className, t, i18n_lang }: Props) {
<div
className={`relative h-20 overflow-hidden rounded-lg bg-white dark:bg-gray-800 ${className}`}
>
<Link href={data.url}>
<a
target='_blank'
onClick={() => onClickLink(data.aid)}
rel='noreferrer'
>
{data.is_reward ? (
<RewardAdContent data={data} t={t} />
) : (
{data.is_reward ? (
i18n_lang != 'zh' ? (
<Link href={PayURL}>
<a target='_blank' rel='noreferrer'>
<RewardAdContent data={data} t={t} />
</a>
</Link>
) : (
<Link href={data.url}>
<a
target='_blank'
onClick={() => onClickLink(data.aid)}
rel='noreferrer'
>
<RewardAdContent data={data} t={t} />:
</a>
</Link>
)
) : (
<Link href={data.url}>
<a
target='_blank'
onClick={() => onClickLink(data.aid)}
rel='noreferrer'
>
<ImageAdContent data={data} handleClose={handleClose} />
)}
</a>
</Link>
</a>
</Link>
)}
</div>
);
}
34 changes: 25 additions & 9 deletions src/pages/article/[aid].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { getClientIP } from '@/utils/util';
import { ArticleProps } from '@/types/article';

const ArticlePage: NextPage<ArticleProps> = ({ article }) => {
const { t } = useTranslation('article');
const { t, i18n } = useTranslation('article');

return (
<>
Expand All @@ -27,13 +27,29 @@ const ArticlePage: NextPage<ArticleProps> = ({ article }) => {
{article.content}
</MDRender>
</article>
<div className='my-2 flex justify-center'>
<ImageWithPreview
className='hidden cursor-zoom-in rounded-lg md:block'
src='https://img.hellogithub.com/ad/footer.png'
alt='weixin_footer'
/>
</div>
{i18n.language === 'zh' ? (
<div className='my-2 flex justify-center'>
<ImageWithPreview
className='hidden cursor-zoom-in rounded-lg md:block'
src='https://img.hellogithub.com/ad/footer.png'
alt='weixin_footer'
/>
</div>
) : (
<a
href='https://www.buymeacoffee.com/hellogithub'
className='flex justify-center'
target='_blank'
rel='noopener noreferrer'
>
<img
src='https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png'
alt='Buy Me A Coffee'
className='h-[60px] w-[217px]'
/>
</a>
)}

<ItemBottom endText='END' />
<ToTop />
</div>
Expand All @@ -51,7 +67,7 @@ export const getServerSideProps: GetServerSideProps = async ({
}) => {
const ip = getClientIP(req);
const aid = query?.aid as string;
const data = await getArticleContent(ip, aid);
const data = await getArticleContent(ip, aid, locale as string);
if (!data.success) {
return {
notFound: true,
Expand Down
8 changes: 6 additions & 2 deletions src/pages/article/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,15 @@ const ArticleIndex: NextPage = () => {
/>
)}
<span className='truncate pr-2 text-sm leading-snug md:pr-0 md:text-base'>
{item.title}
{i18n.language == 'en'
? item.title_en || item.title
: item.title}
</span>
</div>
<div className='pt-1 pb-1.5 pr-1 text-xs leading-loose text-gray-400 line-clamp-2 md:pr-0'>
{item.desc}
{i18n.language == 'en'
? item.desc_en || item.desc
: item.desc}
</div>
<div className='flex items-center text-xs text-gray-800 dark:text-gray-200'>
<div className='truncate whitespace-nowrap md:max-w-xs'>
Expand Down
5 changes: 3 additions & 2 deletions src/services/article.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import { ArticleContentItem, OneItemResp, OneItemsResp } from '@/types/article';

export const getArticleContent = async (
ip: string,
aid: string
aid: string,
locale: string
): Promise<ArticleContentItem> => {
const req: RequestInit = {};
req.headers = { 'x-real-ip': ip, 'x-forwarded-for': ip };
const result = await fetcher<ArticleContentItem>(
makeUrl(`/article/${aid}`),
makeUrl(`/article/${aid}`, { lang: locale }),
req
);
return result;
Expand Down
24 changes: 14 additions & 10 deletions src/services/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,28 @@ function translate(key: string, lang: string): string {
return messages[key]?.[lang] || messages[key]?.['en'] || key;
}

// 获取用户语言的函数
function getUserLanguage(): string {
// 这里可以根据你的应用逻辑来获取用户语言
// 例如,从 localStorage 或 cookie 中获取
console.log(
localStorage.getItem('locale') || navigator.language.split('-')[0] || 'en'
);
return (
localStorage.getItem('locale') || navigator.language.split('-')[0] || 'en'
);
if (typeof window === 'undefined') {
// 服务器端渲染
// 这里可以使用 Next.js 的 API 来获取语言设置
// 例如,从 cookies 或者请求头中获取
// 这个实现需要根据你的具体设置来调整
return 'en'; // 接口异常默认语言
} else {
// 客户端渲染
return (
localStorage?.getItem('locale') ||
navigator?.language?.split('-')[0] ||
'en'
);
}
}

export const fetcher = async function fetcher<T>(
input: RequestInfo,
init?: RequestInit
): Promise<T> {
const lang = getUserLanguage();

// if the user is not online when making the API call
if (typeof window !== 'undefined' && !window.navigator.onLine) {
throw new Error('OFFLINE');
Expand Down
2 changes: 2 additions & 0 deletions src/types/article.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ export interface ItemProps {
export interface ArticleItem {
aid: string;
title: string;
title_en?: string;
head_image: string;
desc: string;
desc_en?: string;
author: string;
is_publish: boolean;
is_hot: boolean;
Expand Down
1 change: 1 addition & 0 deletions src/types/periodical.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface PeriodicalItem {
rid: string;
name: string;
description: string;
description_en: string;
github_url: string;
stars: number;
forks: number;
Expand Down

0 comments on commit bf048f9

Please sign in to comment.