Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ MajdataNet v2. 你可以在 [Branch Legacy](https://github.com/TeamMajdata/Majda
- Framer Motion (动画)
- i18n (国际化支持)

## i18n 约定

语言包位于 `public/i18n`。每个一级 key 使用 `路由/组件` 命名空间,组件内的文案放在该命名空间对象中:

```json
{
"song/SongPage": {
"Download": "Download"
}
}
```

代码中统一通过 `i18n('路由/组件.key')` 使用,例如 `i18n('song/SongPage.Download')`。提交前运行 `pnpm i18n:check`,检查语言包结构、各语言 key 一致性、源码引用和废弃 key。

## 快速开始

### 环境要求
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"scripts": {
"dev": "vite --host",
"build": "tsc -b && vite build",
"i18n:check": "node scripts/check-i18n.mjs",
"lint": "eslint .",
"test": "vitest run",
"test:watch": "vitest",
Expand Down
869 changes: 484 additions & 385 deletions public/i18n/en.json

Large diffs are not rendered by default.

864 changes: 484 additions & 380 deletions public/i18n/ja.json

Large diffs are not rendered by default.

864 changes: 484 additions & 380 deletions public/i18n/ko.json

Large diffs are not rendered by default.

874 changes: 484 additions & 390 deletions public/i18n/zh.json

Large diffs are not rendered by default.

145 changes: 145 additions & 0 deletions scripts/check-i18n.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import fs from 'node:fs';
import path from 'node:path';
import ts from 'typescript';

const root = process.cwd();
const languages = ['en', 'zh', 'ja', 'ko'];
const localeDirectory = path.join(root, 'public', 'i18n');
const sourceDirectory = path.join(root, 'src');
const fullKeyPattern = /^([A-Za-z0-9-]+(?:\/[A-Za-z0-9-]+)+)\.([A-Za-z][A-Za-z0-9_]*)$/;
const namespacePattern = /^[A-Za-z0-9-]+(?:\/[A-Za-z0-9-]+)+$/;
const translationKeyPattern = /^[A-Za-z][A-Za-z0-9_]*$/;
const errors = [];

function addError(message) {
errors.push(message);
}

function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}

function walk(directory) {
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const entryPath = path.join(directory, entry.name);
return entry.isDirectory() ? walk(entryPath) : [entryPath];
});
}

const dictionaries = {};
const flattenedKeys = {};

for (const language of languages) {
const localePath = path.join(localeDirectory, `${language}.json`);
let dictionary;

try {
dictionary = JSON.parse(fs.readFileSync(localePath, 'utf8'));
} catch (error) {
addError(`${path.relative(root, localePath)}: cannot parse JSON (${error.message})`);
continue;
}

if (!isRecord(dictionary)) {
addError(`${path.relative(root, localePath)}: root must be an object`);
continue;
}

const keys = new Set();
for (const [namespace, translations] of Object.entries(dictionary)) {
if (!namespacePattern.test(namespace)) {
addError(`${language}: invalid namespace "${namespace}"; expected route/component`);
}
if (!isRecord(translations)) {
addError(`${language}: namespace "${namespace}" must contain an object`);
continue;
}

for (const [key, value] of Object.entries(translations)) {
if (!translationKeyPattern.test(key)) {
addError(`${language}: invalid key "${namespace}.${key}"`);
}
if (typeof value !== 'string' || value.trim() === '') {
addError(`${language}: "${namespace}.${key}" must be a non-empty string`);
}
keys.add(`${namespace}.${key}`);
}
}

dictionaries[language] = dictionary;
flattenedKeys[language] = keys;
}

const referenceLanguage = languages[0];
const referenceKeys = flattenedKeys[referenceLanguage] ?? new Set();
for (const language of languages.slice(1)) {
const keys = flattenedKeys[language] ?? new Set();
for (const key of referenceKeys) {
if (!keys.has(key)) addError(`${language}: missing translation "${key}"`);
}
for (const key of keys) {
if (!referenceKeys.has(key)) addError(`${language}: extra translation "${key}"`);
}
}

const usedKeys = new Set();
const dynamicCalls = [];
const legacyImports = new Set(['loc', 'useLoc', 'getTranslatedString', 'useTranslation']);

for (const file of walk(sourceDirectory).filter((entry) => /\.(?:ts|tsx)$/.test(entry))) {
const source = fs.readFileSync(file, 'utf8');
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
const relativePath = path.relative(root, file).replaceAll('\\', '/');

function location(node) {
return `${relativePath}:${sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1}`;
}

function visit(node) {
if (ts.isImportSpecifier(node) && legacyImports.has(node.name.text)) {
addError(`${location(node)}: legacy i18n import "${node.name.text}" is not allowed`);
}

if (ts.isStringLiteralLike(node) && referenceKeys.has(node.text)) {
usedKeys.add(node.text);
}

if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'i18n') {
const keyArgument = node.arguments[0];
if (!keyArgument) {
addError(`${location(node)}: i18n() requires a key`);
} else if (ts.isStringLiteralLike(keyArgument)) {
usedKeys.add(keyArgument.text);
if (!fullKeyPattern.test(keyArgument.text)) {
addError(`${location(keyArgument)}: invalid i18n key "${keyArgument.text}"; expected route/component.key`);
}
} else {
dynamicCalls.push(`${location(keyArgument)} (${keyArgument.getText(sourceFile)})`);
}
}

ts.forEachChild(node, visit);
}

visit(sourceFile);
}

for (const key of usedKeys) {
if (!referenceKeys.has(key)) addError(`source references missing translation "${key}"`);
}
for (const key of referenceKeys) {
if (!usedKeys.has(key)) addError(`unused translation "${key}"`);
}

if (errors.length > 0) {
console.error(`i18n check failed with ${errors.length} error(s):`);
for (const error of errors) console.error(`- ${error}`);
process.exitCode = 1;
} else {
console.log(
`i18n check passed: ${languages.length} languages, ${Object.keys(dictionaries[referenceLanguage] ?? {}).length} namespaces, ${referenceKeys.size} keys.`,
);
if (dynamicCalls.length > 0) {
console.log(`Validated ${dynamicCalls.length} dynamic call site(s) through their namespaced source constants.`);
}
}
12 changes: 6 additions & 6 deletions src/components/chart/RecentActivityChart.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import { useLoc } from '@/hooks';
import { useI18n } from '@/hooks';
import type { RecentPlayedData } from '@/types';

// ─── Types ────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -139,7 +139,7 @@ export function buildActivityData(records: RecentPlayedData[]): ActivityData {
// ─── Component ────────────────────────────────────────────────────────────────

export default function RecentActivityChart({ records }: { records: RecentPlayedData[] }) {
const loc = useLoc();
const { i18n } = useI18n();
const activity = useMemo(() => buildActivityData(records), [records]);

if (activity.points.length === 0) return null;
Expand All @@ -160,15 +160,15 @@ export default function RecentActivityChart({ records }: { records: RecentPlayed
<div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
<div>
<div className="text-sm font-bold text-pink-300">
{loc('RecentPlayActivity', '最近游玩活跃度')}
{i18n("shared/RecentActivityChart.RecentPlayActivity", '最近游玩活跃度')}
</div>
<div className="mt-1 text-2xl font-bold text-white">
{activity.rangeLabel} · {activity.total} {loc('Times', '次')}
{activity.rangeLabel} · {activity.total} {i18n("shared/RecentActivityChart.Times", '次')}
</div>
</div>
<div className="text-left text-sm text-white/60 sm:text-right">
<div>{loc('Today', '今日')} {activity.today} {loc('Times', '次')}</div>
<div>{loc('LatestPlay', '最近')} {activity.latestLabel}</div>
<div>{i18n("shared/RecentActivityChart.Today", '今日')} {activity.today} {i18n("shared/RecentActivityChart.Times", '次')}</div>
<div>{i18n("shared/RecentActivityChart.LatestPlay", '最近')} {activity.latestLabel}</div>
</div>
</div>

Expand Down
28 changes: 14 additions & 14 deletions src/components/collection/CollectionCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import useSWR from 'swr';
import { LazyLoad, CoverPic, LoadingSpinner } from '@/components';
import { endpoints } from '@/config/api';
import type { Collection, CollectionSongList } from '@/types';
import { useLoc, useFavorites } from '@/hooks';
import { useI18n, useFavorites } from '@/hooks';

const fetcher = (url: string) => fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json());

Expand All @@ -17,7 +17,7 @@ interface CollectionCardProps {
}

const CollectionCardContent = memo(({ collection, isManaging, onDelete }: CollectionCardProps) => {
const loc = useLoc();
const { i18n } = useI18n();
const navigate = useNavigate();
const { favoriteIds, toggleFavorite, isPending } = useFavorites();

Expand Down Expand Up @@ -52,13 +52,13 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
credentials: 'include',
});
if (res.ok) {
toast.success(loc('DeleteSuccess', '删除成功'));
toast.success(i18n("collection/CollectionCard.DeleteSuccess", '删除成功'));
onDelete?.();
} else {
toast.error(loc('DeleteFailed', '删除失败'));
toast.error(i18n("collection/CollectionCard.DeleteFailed", '删除失败'));
}
} catch {
toast.error(loc('DeleteFailed', '删除失败'));
toast.error(i18n("collection/CollectionCard.DeleteFailed", '删除失败'));
} finally {
setIsDeleting(false);
}
Expand All @@ -85,7 +85,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
<CoverPic id={data.items[currentCoverIndex].id} />
) : (
<div className="flex flex-col justify-center items-center bg-black/60 w-full h-full text-white/50 text-xs">
<span>{loc('NoCover', '无封面')}</span>
<span>{i18n("collection/CollectionCard.NoCover", '无封面')}</span>
</div>
)}
</div>
Expand All @@ -94,10 +94,10 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
<div className="flex flex-col flex-1 p-3 overflow-hidden text-sm">
<div className="font-bold text-white text-lg truncate" title={collection.name}>{collection.name}</div>
<div className="flex-1 mt-1 text-gray-400 line-clamp-2" title={collection.description || ''}>
{collection.description || loc('NoDescription', '暂无描述')}
{collection.description || i18n("collection/CollectionCard.NoDescription", '暂无描述')}
</div>
<div className="mt-1 text-gray-500 truncate">{loc('CreatorLabel', '创建者')}: {collection.createdBy}</div>
<div className="mt-1 text-gray-500 truncate">{loc('CountLabel', '数量')}: {collection.count}</div>
<div className="mt-1 text-gray-500 truncate">{i18n("collection/CollectionCard.CreatorLabel", '创建者')}: {collection.createdBy}</div>
<div className="mt-1 text-gray-500 truncate">{i18n("collection/CollectionCard.CountLabel", '数量')}: {collection.count}</div>
</div>
</div>

Expand All @@ -117,7 +117,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
? 'bg-pink-500/70 hover:bg-pink-500 text-white'
: 'bg-black/30 hover:bg-black/50 text-white/60 hover:text-white'
}`}
title={isFavorited ? loc('Unfavorite', '取消收藏') : loc('Favorite', '收藏')}
title={isFavorited ? i18n("collection/CollectionCard.Unfavorite", '取消收藏') : i18n("collection/CollectionCard.Favorite", '收藏')}
>
{isFavoriteLoading ? (
<LoadingSpinner size="14px" />
Expand All @@ -143,7 +143,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
setConfirmDelete(true);
}}
className="top-2 right-2 z-10 absolute flex justify-center items-center bg-red-500/70 hover:bg-red-500 shadow-lg backdrop-blur-sm border-none rounded-full w-7 h-7 text-white text-sm transition-colors cursor-pointer"
title={loc('Delete', '删除')}
title={i18n("collection/CollectionCard.Delete", '删除')}
>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18" /><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" /><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" /><line x1="10" y1="11" x2="10" y2="17" /><line x1="14" y1="11" x2="14" y2="17" /></svg>
</motion.button>
Expand All @@ -160,7 +160,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
transition={{ duration: 0.15 }}
className="z-20 absolute inset-0 flex flex-col justify-center items-center bg-black/75 backdrop-blur-sm rounded-xl"
>
<p className="mb-3 font-medium text-white text-sm">{loc('ConfirmDeleteCollection', '确认删除此歌单?')}</p>
<p className="mb-3 font-medium text-white text-sm">{i18n("collection/CollectionCard.ConfirmDeleteCollection", '确认删除此歌单?')}</p>
<div className="flex gap-2">
<button
onClick={(e) => {
Expand All @@ -170,7 +170,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
disabled={isDeleting}
className="bg-red-500/80 hover:bg-red-500 disabled:opacity-50 px-4 py-1.5 border-none rounded-lg font-medium text-white text-sm transition-colors cursor-pointer disabled:cursor-not-allowed"
>
{isDeleting ? '...' : loc('Confirm', '确认')}
{isDeleting ? '...' : i18n("collection/CollectionCard.Confirm", '确认')}
</button>
<button
onClick={(e) => {
Expand All @@ -180,7 +180,7 @@ const CollectionCardContent = memo(({ collection, isManaging, onDelete }: Collec
disabled={isDeleting}
className="bg-white/10 hover:bg-white/20 px-4 py-1.5 border-none rounded-lg text-white text-sm transition-colors cursor-pointer disabled:cursor-not-allowed"
>
{loc('Cancel', '取消')}
{i18n("collection/CollectionCard.Cancel", '取消')}
</button>
</div>
</motion.div>
Expand Down
Loading