Compare commits

...

41 Commits

Author SHA1 Message Date
b8cb884e9e Design System 重构继续完成 2026-02-10 04:58:50 +08:00
73d0b0d5fe Design System 重构完成 2026-02-10 03:54:09 +08:00
fe5e8533b5 layout 2026-02-06 04:41:59 +08:00
12eb5c412a layout 2026-02-06 04:36:06 +08:00
3635fbd256 button 2026-02-06 04:13:50 +08:00
058ecf7e39 button 2026-02-06 04:01:41 +08:00
6c7095ffb3 ... 2026-02-06 03:43:49 +08:00
8ed9b011f4 ... 2026-02-06 03:28:53 +08:00
2537b9fe75 ... 2026-02-06 03:22:20 +08:00
5e24fa76a3 ... 2026-02-06 03:16:06 +08:00
9d42a45bb1 ... 2026-02-03 20:29:55 +08:00
d5dde77ee9 ... 2026-02-03 20:00:56 +08:00
c4a9247cad ... 2026-02-03 19:18:29 +08:00
56552863bf ... 2026-02-03 17:27:58 +08:00
0af99b6b70 修改语言图标 2026-02-03 17:04:41 +08:00
eaf97b8279 ... 2026-02-02 23:57:01 +08:00
76749549ff ... 2026-02-02 23:32:39 +08:00
fa6301538b ... 2026-01-22 16:01:07 +08:00
d4d5a53747 补全翻译 2026-01-18 13:06:08 +08:00
ec265be26b 重构 2026-01-14 16:57:35 +08:00
804baa64b2 重构 2026-01-13 23:02:07 +08:00
a1e42127e6 update ignore 2026-01-13 15:17:59 +08:00
f1d706e20c ... 2026-01-13 14:46:27 +08:00
c7cdf40f2f change varchar to text 2026-01-08 10:18:05 +08:00
a55e763525 解决dictionary搜索框溢出问题 2026-01-08 09:45:08 +08:00
9715844eae 宽松化pairs表约束
All checks were successful
continuous-integration/drone/push Build is passing
2026-01-06 19:23:35 +08:00
504ecd259d 增加翻译缓存 2026-01-06 19:11:21 +08:00
06e90687f1 优化词典生成效果 2026-01-06 16:45:52 +08:00
b093ed2b4f 补全翻译 2026-01-06 16:04:53 +08:00
37e221d8b8 ... 2026-01-06 15:41:11 +08:00
f1dcd5afaa ... 2026-01-05 18:37:12 +08:00
66d17df59d 补全翻译
All checks were successful
continuous-integration/drone/push Build is passing
2026-01-05 18:35:12 +08:00
be3eb17490 重构了tts
All checks were successful
continuous-integration/drone/push Build is passing
2026-01-05 17:34:15 +08:00
bd7eca1bd0 before refractor 2026-01-05 16:55:34 +08:00
3bc804c5e8 ... 2026-01-05 14:31:18 +08:00
4c64aa0a40 增加翻译语言 2026-01-05 11:40:11 +08:00
13e8789321 ... 2026-01-05 11:15:35 +08:00
f3b7f86413 取消了memorize folder界面的身份验证
All checks were successful
continuous-integration/drone/push Build is passing
2026-01-04 20:06:57 +08:00
6c4a73d857 优化细节
All checks were successful
continuous-integration/drone/push Build is passing
2026-01-04 16:54:31 +08:00
7c70ec1028 ...
All checks were successful
continuous-integration/drone/push Build is passing
2025-12-29 17:48:04 +08:00
5f24929116 ...
All checks were successful
continuous-integration/drone/push Build is passing
...

...

...

...
2025-12-29 11:49:53 +08:00
195 changed files with 12702 additions and 4020 deletions

View File

@@ -6,3 +6,34 @@ README.md
.next .next
.git .git
certificates certificates
# testing
/coverage
test.ts
test.js
# build outputs
/out/
/build
*.tsbuildinfo
next-env.d.ts
# debug logs
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files
.env*
!.env.example
# misc
.DS_Store
*.pem
.vercel
build.sh
# prisma
/generated/prisma
.claude

View File

@@ -10,3 +10,6 @@ GITHUB_CLIENT_SECRET=
// Database // Database
DATABASE_URL= DATABASE_URL=
// DashScore
DASHSCORE_API_KEY=

3
.gitignore vendored
View File

@@ -46,6 +46,9 @@ next-env.d.ts
build.sh build.sh
test.ts test.ts
test.js
/generated/prisma /generated/prisma
certificates certificates
.claude

View File

@@ -6,5 +6,8 @@
}, },
"[typescriptreact]": { "[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features" "editor.defaultFormatter": "vscode.typescript-language-features"
},
"[css]": {
"editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
} }
} }

128
CLAUDE.md Normal file
View File

@@ -0,0 +1,128 @@
# CLAUDE.md
本文件为 Claude Code (claude.ai/code) 在此代码库中工作时提供指导。
## 项目概述
这是一个基于 Next.js 16 构建的全栈语言学习平台,提供翻译工具、文本转语音、字幕播放、字母学习和记忆功能。平台支持 8 种语言,具有完整的国际化支持。
## 开发命令
```bash
# 启动开发服务器(启用 HTTPS
pnpm run dev
# 构建生产版本standalone 输出模式,用于 Docker
pnpm run build
# 启动生产服务器
pnpm run start
# 代码检查
pnpm run lint
# 数据库操作
# 不要进行数据库操作,让用户操作数据库
```
## 技术栈
- **Next.js 16** 使用 App Router 和 standalone 输出模式
- **React 19** 启用 React Compiler 进行优化
- **TypeScript** 严格模式和 ES2023 目标
- **Tailwind CSS v4** 样式框架
- **PostgreSQL** + **Prisma ORM**(自定义输出目录:`src/generated/prisma`
- **better-auth** 身份验证(邮箱/密码 + OAuth
- **next-intl** 国际化支持en-US, zh-CN, ja-JP, ko-KR, de-DE, fr-FR, it-IT, ug-CN
- **阿里云千问 TTS** (qwen3-tts-flash) 文本转语音
- **pnpm** 包管理器
## 架构设计
### 路由结构
应用使用 Next.js App Router 和基于功能的组织方式:
```
src/app/
├── (features)/ # 功能模块translator, alphabet, memorize, dictionary, srt-player
│ └── [locale]/ # 国际化路由
├── auth/ # 认证页面sign-in, sign-up
├── folders/ # 用户学习文件夹管理
├── users/[username]/# 用户资料页面Server Component
├── profile/ # 重定向到当前用户的资料页面
└── api/ # API 路由
```
### 后端架构模式
项目使用 **Action-Service-Repository 三层架构**
```
src/modules/{module}/
├── {module}-action.ts # Server Actions 层(表单处理、重定向)
├── {module}-action-dto.ts # Action 层 DTOZod 验证)
├── {module}-service.ts # Service 层(业务逻辑)
├── {module}-service-dto.ts # Service 层 DTO
├── {module}-repository.ts # Repository 层(数据库操作)
└── {module}-repository-dto.ts # Repository 层 DTO
```
各层职责:
- **Action 层**:处理表单数据、验证输入、调用 service 层、处理重定向和错误响应
- **Service 层**:实现业务逻辑、调用 better-auth API、协调多个 repository 操作
- **Repository 层**:直接使用 Prisma 进行数据库查询和操作
现有模块:
- `auth` - 认证和用户管理(支持用户名/邮箱登录)
- `folder` - 学习文件夹管理
- `dictionary` - 词典查询
- `translator` - 翻译服务
### 数据库 Schema
核心模型(见 [prisma/schema.prisma](prisma/schema.prisma)
- **User**: 用户中心实体,包含认证信息
- **Folder**: 用户拥有的学习资料容器(级联删除 pairs
- **Pair**: 语言对(翻译/词汇),支持 IPA唯一约束为 (folderId, locale1, locale2, text1)
- **Session/Account**: better-auth 追踪
- **Verification**: 邮箱验证系统
### 核心模式
**Server Actions**: 数据库变更使用 `src/lib/actions/` 中的 Server Actions配合类型安全的 Prisma 操作。
**基于功能的组件**: 每个功能在 `(features)/` 下有自己的路由组,带有 locale 前缀。
**国际化**: 所有面向用户的内容通过 next-intl 处理。消息文件在 `messages/` 目录。locale 自动检测并在路由中前缀。
**认证流程**: better-auth 使用客户端适配器 (`authClient`),通过 hooks 管理会话,受保护的路由使用条件渲染。
**LLM 集成**: 使用智谱 AI API 进行翻译和 IPA 生成。通过环境变量 `ZHIPU_API_KEY``ZHIPU_MODEL_NAME` 配置。
- **Standalone 输出**: 为 Docker 部署配置
- **React Compiler**: 在 `next.config.ts` 中启用以自动优化
- **HTTPS 开发**: 开发服务器使用 `--experimental-https` 标志
- **图片优化**: 通过 remote patterns 允许 GitHub 头像
## 代码组织
- `src/modules/`: 业务模块auth, folder, dictionary, translator
- `src/lib/actions/`: 数据库变更的 Server Actions旧架构正在迁移到 modules
- `src/lib/server/`: 服务端工具AI 集成、认证、翻译器)
- `src/lib/browser/`: 客户端工具
- `src/hooks/`: 自定义 React hooks认证 hooks、会话管理
- `src/i18n/`: 国际化配置
- `messages/`: 各支持语言的翻译文件
- `src/components/`: 可复用的 UI 组件buttons, cards 等)
- `src/shared/`: 共享常量和类型定义
## 开发注意事项
- 使用 pnpm而不是 npm 或 yarn
- 应用使用 TypeScript 严格模式 - 确保类型安全
- 所有面向用户的文本都需要国际化
- **优先使用 Server Components**,只在需要交互时使用 Client Components
- **新功能应遵循 action-service-repository 架构**
- Better-auth 处理会话管理 - 使用 authClient 适配器进行认证操作
- 使用 better-auth username 插件支持用户名登录

View File

@@ -9,7 +9,9 @@
- **SRT字幕播放器** - 结合视频字幕学习,支持多种字幕格式 - **SRT字幕播放器** - 结合视频字幕学习,支持多种字幕格式
- **字母学习模块** - 针对初学者的字母和发音基础学习 - **字母学习模块** - 针对初学者的字母和发音基础学习
- **记忆强化工具** - 通过科学记忆法巩固学习内容 - **记忆强化工具** - 通过科学记忆法巩固学习内容
- **词典查询** - 查询单词和短语,提供详细释义和例句
- **个人学习空间** - 用户可以创建、管理和组织自己的学习资料 - **个人学习空间** - 用户可以创建、管理和组织自己的学习资料
- **用户资料系统** - 支持用户名登录、个人资料页面展示
## 🛠 技术栈 ## 🛠 技术栈
@@ -26,7 +28,7 @@
### 国际化与辅助功能 ### 国际化与辅助功能
- **next-intl** - 国际化解决方案 - **next-intl** - 国际化解决方案
- **edge-tts-universal** - 跨平台文本转语音 - **阿里云千问 TTS** - qwen3-tts-flash 语音合成
### 开发工具 ### 开发工具
- **ESLint** - 代码质量检查 - **ESLint** - 代码质量检查
@@ -38,8 +40,16 @@
src/ src/
├── app/ # Next.js App Router 路由 ├── app/ # Next.js App Router 路由
│ ├── (features)/ # 功能模块路由 │ ├── (features)/ # 功能模块路由
│ ├── api/ # API 路由 │ ├── auth/ # 认证相关页面
── auth/ # 认证相关页面 ── profile/ # 用户资料重定向
│ ├── users/[username]/ # 用户资料页面
│ ├── folders/ # 文件夹管理
│ └── api/ # API 路由
├── modules/ # 业务模块action-service-repository 架构)
│ ├── auth/ # 认证模块
│ ├── folder/ # 文件夹模块
│ ├── dictionary/ # 词典模块
│ └── translator/ # 翻译模块
├── components/ # React 组件 ├── components/ # React 组件
│ ├── buttons/ # 按钮组件 │ ├── buttons/ # 按钮组件
│ ├── cards/ # 卡片组件 │ ├── cards/ # 卡片组件
@@ -50,6 +60,7 @@ src/
│ └── server/ # 服务器端工具 │ └── server/ # 服务器端工具
├── hooks/ # 自定义 React Hooks ├── hooks/ # 自定义 React Hooks
├── i18n/ # 国际化配置 ├── i18n/ # 国际化配置
├── shared/ # 共享常量和类型
└── config/ # 应用配置 └── config/ # 应用配置
``` ```
@@ -57,7 +68,7 @@ src/
### 环境要求 ### 环境要求
- Node.js 24 - Node.js 23
- PostgreSQL 数据库 - PostgreSQL 数据库
- pnpm (推荐) 或 npm - pnpm (推荐) 或 npm
@@ -85,17 +96,20 @@ cp .env.example .env.local
然后编辑 `.env.local` 文件,配置所有必要的环境变量: 然后编辑 `.env.local` 文件,配置所有必要的环境变量:
```env ```env
// LLM # LLM 集成(智谱 AI 用于翻译和 IPA 生成)
ZHIPU_API_KEY=your-zhipu-api-key ZHIPU_API_KEY=your-zhipu-api-key
ZHIPU_MODEL_NAME=your-zhipu-model-name ZHIPU_MODEL_NAME=your-zhipu-model-name
// Auth # 阿里云千问 TTS文本转语音
DASHSCORE_API_KEY=your-dashscore-api-key
# 认证
BETTER_AUTH_SECRET=your-better-auth-secret BETTER_AUTH_SECRET=your-better-auth-secret
BETTER_AUTH_URL=http://localhost:3000 BETTER_AUTH_URL=http://localhost:3000
GITHUB_CLIENT_ID=your-github-client-id GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret GITHUB_CLIENT_SECRET=your-github-client-secret
// Database # 数据库
DATABASE_URL=postgresql://username:password@localhost:5432/database_name DATABASE_URL=postgresql://username:password@localhost:5432/database_name
``` ```
@@ -118,14 +132,27 @@ pnpm run dev
### 认证系统 ### 认证系统
应用使用 better-auth 提供安全的用户认证系统,支持邮箱/密码登录和第三方登录。 应用使用 better-auth 提供安全的用户认证系统,支持
- 邮箱/密码登录和注册
- **用户名登录**(可通过用户名或邮箱登录)
- GitHub OAuth 第三方登录
- 邮箱验证功能
### 后端架构
项目采用 **Action-Service-Repository 三层架构**
- **Action 层**:处理 Server Actions、表单验证、重定向
- **Service 层**业务逻辑、better-auth 集成
- **Repository 层**Prisma 数据库操作
### 数据模型 ### 数据模型
核心数据模型包括: 核心数据模型包括:
- **User** - 用户信息 - **User** - 用户信息(支持用户名、邮箱、头像)
- **Folder** - 学习资料文件夹 - **Folder** - 学习资料文件夹
- **Pair** - 语言对(翻译对、词汇对等) - **Pair** - 语言对(翻译对、词汇对等)
- **Session/Account** - 认证会话追踪
- **Verification** - 邮箱验证系统
详细模型定义请参考 [prisma/schema.prisma](./prisma/schema.prisma) 详细模型定义请参考 [prisma/schema.prisma](./prisma/schema.prisma)

258
messages/de-DE.json Normal file
View File

@@ -0,0 +1,258 @@
{
"alphabet": {
"chooseCharacters": "Bitte wählen Sie die Zeichen aus, die Sie lernen möchten",
"japanese": "Japanische Kana",
"english": "Englisches Alphabet",
"uyghur": "Uigurisches Alphabet",
"esperanto": "Esperanto-Alphabet",
"loading": "Laden...",
"loadFailed": "Laden fehlgeschlagen, bitte versuchen Sie es erneut",
"hideLetter": "Zeichen ausblenden",
"showLetter": "Zeichen anzeigen",
"hideIPA": "IPA ausblenden",
"showIPA": "IPA anzeigen",
"roman": "Romanisierung",
"letter": "Zeichen",
"random": "Zufälliger Modus",
"randomNext": "Zufällig weiter"
},
"folders": {
"title": "Ordner",
"subtitle": "Verwalten Sie Ihre Sammlungen",
"newFolder": "Neuer Ordner",
"creating": "Erstellen...",
"noFoldersYet": "Noch keine Ordner",
"folderInfo": "ID: {id} • {totalPairs} Paare",
"enterFolderName": "Ordnernamen eingeben:",
"confirmDelete": "Geben Sie \"{name}\" ein, um zu löschen:"
},
"folder_id": {
"unauthorized": "Sie sind nicht der Eigentümer dieses Ordners",
"back": "Zurück",
"textPairs": "Textpaare",
"itemsCount": "{count} Elemente",
"memorize": "Einprägen",
"loadingTextPairs": "Textpaare werden geladen...",
"noTextPairs": "Keine Textpaare in diesem Ordner",
"addNewTextPair": "Neues Textpaar hinzufügen",
"add": "Hinzufügen",
"updateTextPair": "Textpaar aktualisieren",
"update": "Aktualisieren",
"text1": "Text 1",
"text2": "Text 2",
"language1": "Sprache 1",
"language2": "Sprache 2",
"enterLanguageName": "Bitte geben Sie den Sprachennamen ein",
"edit": "Bearbeiten",
"delete": "Löschen",
"permissionDenied": "Sie haben keine Berechtigung, diese Aktion auszuführen",
"error": {
"update": "Sie haben keine Berechtigung, dieses Element zu aktualisieren.",
"delete": "Sie haben keine Berechtigung, dieses Element zu löschen.",
"add": "Sie haben keine Berechtigung, Elemente zu diesem Ordner hinzuzufügen.",
"rename": "Sie haben keine Berechtigung, diesen Ordner umzubenennen.",
"deleteFolder": "Sie haben keine Berechtigung, diesen Ordner zu löschen."
}
},
"home": {
"title": "Sprachen lernen",
"description": "Hier ist eine sehr nützliche Website, die Ihnen hilft, fast jede Sprache der Welt zu lernen, einschließlich konstruierter Sprachen.",
"explore": "Erkunden",
"fortune": {
"quote": "Bleib hungrig, bleiv dumm.",
"author": "— Steve Jobs"
},
"translator": {
"name": "Übersetzer",
"description": "In jede Sprache übersetzen und mit Internationalem Phonetischem Alphabet (IPA) annotieren"
},
"textSpeaker": {
"name": "Text-Sprecher",
"description": "Text erkennen und vorlesen, unterstützt Schleifenwiedergabe und Geschwindigkeitsanpassung"
},
"srtPlayer": {
"name": "SRT-Videoplayer",
"description": "Videos basierend auf SRT-Untertiteldateien satzweise abspielen, um die Aussprache von Muttersprachlern zu imitieren"
},
"alphabet": {
"name": "Alphabet",
"description": "Beginnen Sie mit dem Erlernen einer neuen Sprache mit dem Alphabet"
},
"memorize": {
"name": "Einprägen",
"description": "Sprache A zu Sprache B, Sprache B zu Sprache A, unterstützt Diktat"
},
"dictionary": {
"name": "Wörterbuch",
"description": "Wörter und Redewendungen nachschlagen mit detaillierten Definitionen und Beispielen"
},
"moreFeatures": {
"name": "Weitere Funktionen",
"description": "In Entwicklung, bleiben Sie dran"
}
},
"auth": {
"title": "Authentifizierung",
"signIn": "Anmelden",
"signUp": "Registrieren",
"email": "E-Mail",
"password": "Passwort",
"confirmPassword": "Passwort bestätigen",
"name": "Name",
"signInButton": "Anmelden",
"signUpButton": "Registrieren",
"noAccount": "Haben Sie kein Konto?",
"hasAccount": "Haben Sie bereits ein Konto?",
"signInWithGitHub": "Mit GitHub anmelden",
"signUpWithGitHub": "Mit GitHub registrieren",
"invalidEmail": "Bitte geben Sie eine gültige E-Mail-Adresse ein",
"passwordTooShort": "Das Passwort muss mindestens 8 Zeichen lang sein",
"passwordsNotMatch": "Passwörter stimmen nicht überein",
"nameRequired": "Bitte geben Sie Ihren Namen ein",
"emailRequired": "Bitte geben Sie Ihre E-Mail ein",
"passwordRequired": "Bitte geben Sie Ihr Passwort ein",
"confirmPasswordRequired": "Bitte bestätigen Sie Ihr Passwort",
"loading": "Laden..."
},
"memorize": {
"folder_selector": {
"selectFolder": "Wählen Sie einen Ordner aus",
"noFolders": "Keine Ordner gefunden",
"folderInfo": "{id}. {name} ({count})"
},
"memorize": {
"answer": "Antwort",
"next": "Weiter",
"reverse": "Umkehren",
"dictation": "Diktat",
"noTextPairs": "Keine Textpaare verfügbar",
"disorder": "Mischen",
"previous": "Zurück"
},
"page": {
"unauthorized": "Sie sind nicht berechtigt, auf diesen Ordner zuzugreifen"
}
},
"navbar": {
"title": "learn-languages",
"sourceCode": "GitHub",
"sign_in": "Anmelden",
"profile": "Profil",
"folders": "Ordner"
},
"profile": {
"myProfile": "Mein Profil",
"email": "E-Mail: {email}",
"logout": "Abmelden"
},
"srt_player": {
"uploadVideo": "Video hochladen",
"uploadSubtitle": "Untertitel hochladen",
"pause": "Pause",
"play": "Abspielen",
"previous": "Zurück",
"next": "Weiter",
"restart": "Neustart",
"autoPause": "Auto-Pause ({enabled})",
"uploadVideoAndSubtitle": "Bitte laden Sie Video- und Untertiteldateien hoch",
"uploadVideoFile": "Bitte laden Sie eine Videodatei hoch",
"uploadSubtitleFile": "Bitte laden Sie eine Untertiteldatei hoch",
"processingSubtitle": "Untertiteldatei wird verarbeitet...",
"needBothFiles": "Sowohl Video- als auch Untertiteldateien sind erforderlich, um mit dem Lernen zu beginnen",
"videoFile": "Videodatei",
"subtitleFile": "Untertiteldatei",
"uploaded": "Hochgeladen",
"notUploaded": "Nicht hochgeladen",
"upload": "Hochladen",
"autoPauseStatus": "Auto-Pause: {enabled}",
"on": "Ein",
"off": "Aus",
"videoUploadFailed": "Video-Upload fehlgeschlagen",
"subtitleUploadFailed": "Untertitel-Upload fehlgeschlagen"
},
"text_speaker": {
"generateIPA": "IPA generieren",
"viewSavedItems": "Gespeicherte Elemente anzeigen",
"confirmDeleteAll": "Sind Sie sicher, dass Sie alles löschen möchten? (J/N)"
},
"translator": {
"detectLanguage": "Sprache erkennen",
"generateIPA": "IPA generieren",
"translateInto": "Übersetzen in",
"chinese": "Chinesisch",
"english": "Englisch",
"french": "Französisch",
"german": "Deutsch",
"italian": "Italienisch",
"japanese": "Japanisch",
"korean": "Koreanisch",
"portuguese": "Portugiesisch",
"russian": "Russisch",
"spanish": "Spanisch",
"other": "Andere",
"translating": "Übersetzung läuft...",
"translate": "Übersetzen",
"inputLanguage": "Geben Sie eine Sprache ein.",
"history": "Verlauf",
"enterLanguage": "Sprache eingeben",
"add_to_folder": {
"notAuthenticated": "Sie sind nicht authentifiziert",
"chooseFolder": "Wählen Sie einen Ordner zum Hinzufügen aus",
"noFolders": "Keine Ordner gefunden",
"folderInfo": "{id}. {name}",
"close": "Schließen",
"success": "Textpaar zum Ordner hinzugefügt",
"error": "Textpaar konnte nicht zum Ordner hinzugefügt werden"
},
"autoSave": "Automatisch speichern"
},
"dictionary": {
"title": "Wörterbuch",
"description": "Wörter und Ausdrücke mit detaillierten Definitionen und Beispielen nachschlagen",
"searchPlaceholder": "Wort oder Ausdruck zum Nachschlagen eingeben...",
"searching": "Suche...",
"search": "Suchen",
"languageSettings": "Spracheinstellungen",
"queryLanguage": "Abfragesprache",
"queryLanguageHint": "Welche Sprache hat das Wort/die Phrase, die Sie nachschlagen möchten",
"definitionLanguage": "Definitionssprache",
"definitionLanguageHint": "In welcher Sprache möchten Sie die Definitionen sehen",
"otherLanguagePlaceholder": "Oder eine andere Sprache eingeben...",
"currentSettings": "Aktuelle Einstellungen: Abfrage {queryLang}, Definition {definitionLang}",
"relookup": "Neu suchen",
"saveToFolder": "In Ordner speichern",
"loading": "Laden...",
"noResults": "Keine Ergebnisse gefunden",
"tryOtherWords": "Versuchen Sie andere Wörter oder Ausdrücke",
"welcomeTitle": "Willkommen beim Wörterbuch",
"welcomeHint": "Geben Sie oben im Suchfeld ein Wort oder einen Ausdruck ein, um zu suchen",
"lookupFailed": "Suche fehlgeschlagen, bitte später erneut versuchen",
"relookupSuccess": "Erfolgreich neu gesucht",
"relookupFailed": "Wörterbuch Neu-Suche fehlgeschlagen",
"pleaseLogin": "Bitte melden Sie sich zuerst an",
"pleaseCreateFolder": "Bitte erstellen Sie zuerst einen Ordner",
"savedToFolder": "Im Ordner gespeichert: {folderName}",
"saveFailed": "Speichern fehlgeschlagen, bitte später erneut versuchen"
},
"user_profile": {
"anonymous": "Anonym",
"email": "E-Mail",
"verified": "Verifiziert",
"unverified": "Nicht verifiziert",
"accountInfo": "Kontoinformationen",
"userId": "Benutzer-ID",
"username": "Benutzername",
"displayName": "Anzeigename",
"notSet": "Nicht festgelegt",
"memberSince": "Mitglied seit",
"folders": {
"title": "Ordner",
"noFolders": "Noch keine Ordner",
"folderName": "Ordnername",
"totalPairs": "Anzahl der Paare",
"createdAt": "Erstellt am",
"actions": "Aktionen",
"view": "Ansehen"
}
}
}

View File

@@ -22,13 +22,9 @@
"newFolder": "New Folder", "newFolder": "New Folder",
"creating": "Creating...", "creating": "Creating...",
"noFoldersYet": "No folders yet", "noFoldersYet": "No folders yet",
"folderInfo": "{id}. {name} ({totalPairs})", "folderInfo": "ID: {id} • {totalPairs} pairs",
"enterFolderName": "Enter folder name:", "enterFolderName": "Enter folder name:",
"confirmDelete": "Type \"{name}\" to delete:", "confirmDelete": "Type \"{name}\" to delete:"
"createFolderSuccess": "Folder created successfully",
"deleteFolderSuccess": "Folder deleted successfully",
"createFolderError": "Failed to create folder",
"deleteFolderError": "Failed to delete folder"
}, },
"folder_id": { "folder_id": {
"unauthorized": "You are not the owner of this folder", "unauthorized": "You are not the owner of this folder",
@@ -44,10 +40,19 @@
"update": "Update", "update": "Update",
"text1": "Text 1", "text1": "Text 1",
"text2": "Text 2", "text2": "Text 2",
"locale1": "Locale 1", "language1": "Locale 1",
"locale2": "Locale 2", "language2": "Locale 2",
"enterLanguageName": "Please enter language name",
"edit": "Edit", "edit": "Edit",
"delete": "Delete" "delete": "Delete",
"permissionDenied": "You do not have permission to perform this action",
"error": {
"update": "You do not have permission to update this item.",
"delete": "You do not have permission to delete this item.",
"add": "You do not have permission to add items to this folder.",
"rename": "You do not have permission to rename this folder.",
"deleteFolder": "You do not have permission to delete this folder."
}
}, },
"home": { "home": {
"title": "Learn Languages", "title": "Learn Languages",
@@ -77,15 +82,15 @@
"name": "Memorize", "name": "Memorize",
"description": "Language A to Language B, Language B to Language A, supports dictation" "description": "Language A to Language B, Language B to Language A, supports dictation"
}, },
"dictionary": {
"name": "Dictionary",
"description": "Look up words and phrases with detailed definitions and examples"
},
"moreFeatures": { "moreFeatures": {
"name": "More Features", "name": "More Features",
"description": "Under development, stay tuned" "description": "Under development, stay tuned"
} }
}, },
"login": {
"loading": "Loading...",
"githubLogin": "GitHub Login"
},
"auth": { "auth": {
"title": "Authentication", "title": "Authentication",
"signIn": "Sign In", "signIn": "Sign In",
@@ -94,6 +99,8 @@
"password": "Password", "password": "Password",
"confirmPassword": "Confirm Password", "confirmPassword": "Confirm Password",
"name": "Name", "name": "Name",
"username": "Username",
"emailOrUsername": "Email or Username",
"signInButton": "Sign In", "signInButton": "Sign In",
"signUpButton": "Sign Up", "signUpButton": "Sign Up",
"noAccount": "Don't have an account?", "noAccount": "Don't have an account?",
@@ -103,10 +110,12 @@
"invalidEmail": "Please enter a valid email address", "invalidEmail": "Please enter a valid email address",
"passwordTooShort": "Password must be at least 8 characters", "passwordTooShort": "Password must be at least 8 characters",
"passwordsNotMatch": "Passwords do not match", "passwordsNotMatch": "Passwords do not match",
"signInFailed": "Sign in failed, please check your email and password",
"signUpFailed": "Sign up failed, please try again later",
"nameRequired": "Please enter your name", "nameRequired": "Please enter your name",
"usernameRequired": "Please enter a username",
"usernameTooShort": "Username must be at least 3 characters",
"usernameInvalid": "Username can only contain letters, numbers, and underscores",
"emailRequired": "Please enter your email", "emailRequired": "Please enter your email",
"identifierRequired": "Please enter your email or username",
"passwordRequired": "Please enter your password", "passwordRequired": "Please enter your password",
"confirmPasswordRequired": "Please confirm your password", "confirmPasswordRequired": "Please confirm your password",
"loading": "Loading..." "loading": "Loading..."
@@ -151,18 +160,6 @@
"next": "Next", "next": "Next",
"restart": "Restart", "restart": "Restart",
"autoPause": "Auto Pause ({enabled})", "autoPause": "Auto Pause ({enabled})",
"playbackSpeed": "Playback Speed",
"subtitleSettings": "Subtitle Settings",
"fontSize": "Font Size",
"backgroundColor": "Background Color",
"textColor": "Text Color",
"fontFamily": "Font Family",
"opacity": "Opacity",
"position": "Position",
"top": "Top",
"center": "Center",
"bottom": "Bottom",
"keyboardShortcuts": "Keyboard Shortcuts",
"uploadVideoAndSubtitle": "Please upload video and subtitle files", "uploadVideoAndSubtitle": "Please upload video and subtitle files",
"uploadVideoFile": "Please upload video file", "uploadVideoFile": "Please upload video file",
"uploadSubtitleFile": "Please upload subtitle file", "uploadSubtitleFile": "Please upload subtitle file",
@@ -177,16 +174,7 @@
"on": "On", "on": "On",
"off": "Off", "off": "Off",
"videoUploadFailed": "Video upload failed", "videoUploadFailed": "Video upload failed",
"subtitleUploadFailed": "Subtitle upload failed", "subtitleUploadFailed": "Subtitle upload failed"
"subtitleLoadSuccess": "Subtitle file loaded successfully",
"subtitleLoadFailed": "Subtitle file loading failed",
"shortcuts": {
"playPause": "Play/Pause",
"next": "Next",
"previous": "Previous",
"restart": "Restart",
"autoPause": "Toggle Auto Pause"
}
}, },
"text_speaker": { "text_speaker": {
"generateIPA": "Generate IPA", "generateIPA": "Generate IPA",
@@ -199,7 +187,14 @@
"translateInto": "translate into", "translateInto": "translate into",
"chinese": "Chinese", "chinese": "Chinese",
"english": "English", "english": "English",
"french": "French",
"german": "German",
"italian": "Italian", "italian": "Italian",
"japanese": "Japanese",
"korean": "Korean",
"portuguese": "Portuguese",
"russian": "Russian",
"spanish": "Spanish",
"other": "Other", "other": "Other",
"translating": "translating...", "translating": "translating...",
"translate": "translate", "translate": "translate",
@@ -216,5 +211,54 @@
"error": "Failed to add text pair to folder" "error": "Failed to add text pair to folder"
}, },
"autoSave": "Auto Save" "autoSave": "Auto Save"
},
"dictionary": {
"title": "Dictionary",
"description": "Look up words and phrases with detailed definitions and examples",
"searchPlaceholder": "Enter a word or phrase to look up...",
"searching": "Searching...",
"search": "Search",
"languageSettings": "Language Settings",
"queryLanguage": "Query Language",
"queryLanguageHint": "What language is the word/phrase you want to look up",
"definitionLanguage": "Definition Language",
"definitionLanguageHint": "What language do you want the definitions in",
"otherLanguagePlaceholder": "Or enter another language...",
"currentSettings": "Current settings: Query {queryLang}, Definition {definitionLang}",
"relookup": "Re-search",
"saveToFolder": "Save to folder",
"loading": "Loading...",
"noResults": "No results found",
"tryOtherWords": "Try other words or phrases",
"welcomeTitle": "Welcome to Dictionary",
"welcomeHint": "Enter a word or phrase in the search box above to start looking up",
"lookupFailed": "Search failed, please try again later",
"relookupSuccess": "Re-searched successfully",
"relookupFailed": "Dictionary re-search failed",
"pleaseLogin": "Please log in first",
"pleaseCreateFolder": "Please create a folder first",
"savedToFolder": "Saved to folder: {folderName}",
"saveFailed": "Save failed, please try again later"
},
"user_profile": {
"anonymous": "Anonymous",
"email": "Email",
"verified": "Verified",
"unverified": "Unverified",
"accountInfo": "Account Information",
"userId": "User ID",
"username": "Username",
"displayName": "Display Name",
"notSet": "Not Set",
"memberSince": "Member Since",
"folders": {
"title": "Folders",
"noFolders": "No folders yet",
"folderName": "Folder Name",
"totalPairs": "Total Pairs",
"createdAt": "Created At",
"actions": "Actions",
"view": "View"
}
} }
} }

258
messages/fr-FR.json Normal file
View File

@@ -0,0 +1,258 @@
{
"alphabet": {
"chooseCharacters": "Veuillez sélectionner les caractères que vous souhaitez apprendre",
"japanese": "Kana japonais",
"english": "Alphabet anglais",
"uyghur": "Alphabet ouïghour",
"esperanto": "Alphabet espéranto",
"loading": "Chargement...",
"loadFailed": "Échec du chargement, veuillez réessayer",
"hideLetter": "Masquer la lettre",
"showLetter": "Afficher la lettre",
"hideIPA": "Masquer l'API",
"showIPA": "Afficher l'API",
"roman": "Romanisation",
"letter": "Lettre",
"random": "Mode aléatoire",
"randomNext": "Suivant aléatoire"
},
"folders": {
"title": "Dossiers",
"subtitle": "Gérez vos collections",
"newFolder": "Nouveau dossier",
"creating": "Création...",
"noFoldersYet": "Aucun dossier pour le moment",
"folderInfo": "ID: {id} • {totalPairs} paires",
"enterFolderName": "Entrez le nom du dossier:",
"confirmDelete": "Tapez \"{name}\" pour supprimer:"
},
"folder_id": {
"unauthorized": "Vous n'êtes pas le propriétaire de ce dossier",
"back": "Retour",
"textPairs": "Paires de textes",
"itemsCount": "{count} éléments",
"memorize": "Mémoriser",
"loadingTextPairs": "Chargement des paires de textes...",
"noTextPairs": "Aucune paire de textes dans ce dossier",
"addNewTextPair": "Ajouter une nouvelle paire de textes",
"add": "Ajouter",
"updateTextPair": "Mettre à jour la paire de textes",
"update": "Mettre à jour",
"text1": "Texte 1",
"text2": "Texte 2",
"language1": "Langue 1",
"language2": "Langue 2",
"enterLanguageName": "Veuillez entrer le nom de la langue",
"edit": "Modifier",
"delete": "Supprimer",
"permissionDenied": "Vous n'avez pas la permission d'effectuer cette action",
"error": {
"update": "Vous n'avez pas la permission de mettre à jour cet élément.",
"delete": "Vous n'avez pas la permission de supprimer cet élément.",
"add": "Vous n'avez pas la permission d'ajouter des éléments à ce dossier.",
"rename": "Vous n'avez pas la permission de renommer ce dossier.",
"deleteFolder": "Vous n'avez pas la permission de supprimer ce dossier."
}
},
"home": {
"title": "Apprendre les langues",
"description": "Voici un site web très utile pour vous aider à apprendre presque toutes les langues du monde, y compris les langues construites.",
"explore": "Explorer",
"fortune": {
"quote": "Stay hungry, stay foolish.",
"author": "— Steve Jobs"
},
"translator": {
"name": "Traducteur",
"description": "Traduire dans n'importe quelle langue et annoter avec l'alphabet phonétique international (API)"
},
"textSpeaker": {
"name": "Lecteur de texte",
"description": "Reconnaître et lire le texte à haute voix, prend en charge la lecture en boucle et le réglage de la vitesse"
},
"srtPlayer": {
"name": "Lecteur vidéo SRT",
"description": "Lire des vidéos phrase par phrase basées sur des fichiers de sous-titres SRT pour imiter la prononciation des locuteurs natifs"
},
"alphabet": {
"name": "Alphabet",
"description": "Commencer à apprendre une nouvelle langue par l'alphabet"
},
"memorize": {
"name": "Mémoriser",
"description": "Langue A vers langue B, langue B vers langue A, prend en charge la dictée"
},
"dictionary": {
"name": "Dictionnaire",
"description": "Rechercher des mots et des phrases avec des définitions détaillées et des exemples"
},
"moreFeatures": {
"name": "Plus de fonctionnalités",
"description": "En développement, restez à l'écoute"
}
},
"auth": {
"title": "Authentification",
"signIn": "Se connecter",
"signUp": "S'inscrire",
"email": "E-mail",
"password": "Mot de passe",
"confirmPassword": "Confirmer le mot de passe",
"name": "Nom",
"signInButton": "Se connecter",
"signUpButton": "S'inscrire",
"noAccount": "Vous n'avez pas de compte?",
"hasAccount": "Vous avez déjà un compte?",
"signInWithGitHub": "Se connecter avec GitHub",
"signUpWithGitHub": "S'inscrire avec GitHub",
"invalidEmail": "Veuillez entrer une adresse e-mail valide",
"passwordTooShort": "Le mot de passe doit contenir au moins 8 caractères",
"passwordsNotMatch": "Les mots de passe ne correspondent pas",
"nameRequired": "Veuillez entrer votre nom",
"emailRequired": "Veuillez entrer votre e-mail",
"passwordRequired": "Veuillez entrer votre mot de passe",
"confirmPasswordRequired": "Veuillez confirmer votre mot de passe",
"loading": "Chargement..."
},
"memorize": {
"folder_selector": {
"selectFolder": "Sélectionner un dossier",
"noFolders": "Aucun dossier trouvé",
"folderInfo": "{id}. {name} ({count})"
},
"memorize": {
"answer": "Réponse",
"next": "Suivant",
"reverse": "Inverser",
"dictation": "Dictée",
"noTextPairs": "Aucune paire de textes disponible",
"disorder": "Désordre",
"previous": "Précédent"
},
"page": {
"unauthorized": "Vous n'êtes pas autorisé à accéder à ce dossier"
}
},
"navbar": {
"title": "learn-languages",
"sourceCode": "GitHub",
"sign_in": "Se connecter",
"profile": "Profil",
"folders": "Dossiers"
},
"profile": {
"myProfile": "Mon profil",
"email": "E-mail: {email}",
"logout": "Se déconnecter"
},
"srt_player": {
"uploadVideo": "Télécharger une vidéo",
"uploadSubtitle": "Télécharger des sous-titres",
"pause": "Pause",
"play": "Lire",
"previous": "Précédent",
"next": "Suivant",
"restart": "Redémarrer",
"autoPause": "Pause automatique ({enabled})",
"uploadVideoAndSubtitle": "Veuillez télécharger des fichiers vidéo et de sous-titres",
"uploadVideoFile": "Veuillez télécharger un fichier vidéo",
"uploadSubtitleFile": "Veuillez télécharger un fichier de sous-titres",
"processingSubtitle": "Traitement du fichier de sous-titres...",
"needBothFiles": "Les fichiers vidéo et de sous-titres sont requis pour commencer l'apprentissage",
"videoFile": "Fichier vidéo",
"subtitleFile": "Fichier de sous-titres",
"uploaded": "Téléchargé",
"notUploaded": "Non téléchargé",
"upload": "Télécharger",
"autoPauseStatus": "Pause automatique: {enabled}",
"on": "Activé",
"off": "Désactivé",
"videoUploadFailed": "Échec du téléchargement de la vidéo",
"subtitleUploadFailed": "Échec du téléchargement des sous-titres"
},
"text_speaker": {
"generateIPA": "Générer l'API",
"viewSavedItems": "Voir les éléments enregistrés",
"confirmDeleteAll": "Êtes-vous sûr de vouloir tout supprimer? (O/N)"
},
"translator": {
"detectLanguage": "détecter la langue",
"generateIPA": "générer l'api",
"translateInto": "traduire en",
"chinese": "Chinois",
"english": "Anglais",
"french": "Français",
"german": "Allemand",
"italian": "Italien",
"japanese": "Japonais",
"korean": "Coréen",
"portuguese": "Portugais",
"russian": "Russe",
"spanish": "Espagnol",
"other": "Autre",
"translating": "traduction...",
"translate": "traduire",
"inputLanguage": "Entrez une langue.",
"history": "Historique",
"enterLanguage": "Entrer la langue",
"add_to_folder": {
"notAuthenticated": "Vous n'êtes pas authentifié",
"chooseFolder": "Choisir un dossier à ajouter",
"noFolders": "Aucun dossier trouvé",
"folderInfo": "{id}. {name}",
"close": "Fermer",
"success": "Paire de textes ajoutée au dossier",
"error": "Échec de l'ajout de la paire de textes au dossier"
},
"autoSave": "Sauvegarde automatique"
},
"dictionary": {
"title": "Dictionnaire",
"description": "Rechercher des mots et des phrases avec des définitions détaillées et des exemples",
"searchPlaceholder": "Entrez un mot ou une phrase à rechercher...",
"searching": "Recherche...",
"search": "Rechercher",
"languageSettings": "Paramètres linguistiques",
"queryLanguage": "Langue de requête",
"queryLanguageHint": "Quelle est la langue du mot/phrase que vous souhaitez rechercher",
"definitionLanguage": "Langue de définition",
"definitionLanguageHint": "Dans quelle langue souhaitez-vous voir les définitions",
"otherLanguagePlaceholder": "Ou entrez une autre langue...",
"currentSettings": "Paramètres actuels : Requête {queryLang}, Définition {definitionLang}",
"relookup": "Rechercher à nouveau",
"saveToFolder": "Enregistrer dans le dossier",
"loading": "Chargement...",
"noResults": "Aucun résultat trouvé",
"tryOtherWords": "Essayez d'autres mots ou phrases",
"welcomeTitle": "Bienvenue dans le dictionnaire",
"welcomeHint": "Entrez un mot ou une phrase dans la zone de recherche ci-dessus pour commencer",
"lookupFailed": "Recherche échouée, veuillez réessayer plus tard",
"relookupSuccess": "Recherche répétée avec succès",
"relookupFailed": "Nouvelle recherche de dictionnaire échouée",
"pleaseLogin": "Veuillez d'abord vous connecter",
"pleaseCreateFolder": "Veuillez d'abord créer un dossier",
"savedToFolder": "Enregistré dans le dossier : {folderName}",
"saveFailed": "Échec de l'enregistrement, veuillez réessayer plus tard"
},
"user_profile": {
"anonymous": "Anonyme",
"email": "E-mail",
"verified": "Vérifié",
"unverified": "Non vérifié",
"accountInfo": "Informations du compte",
"userId": "ID utilisateur",
"username": "Nom d'utilisateur",
"displayName": "Nom d'affichage",
"notSet": "Non défini",
"memberSince": "Membre depuis",
"folders": {
"title": "Dossiers",
"noFolders": "Aucun dossier pour le moment",
"folderName": "Nom du dossier",
"totalPairs": "Nombre de paires",
"createdAt": "Créé le",
"actions": "Actions",
"view": "Voir"
}
}
}

258
messages/it-IT.json Normal file
View File

@@ -0,0 +1,258 @@
{
"alphabet": {
"chooseCharacters": "Seleziona i caratteri che desideri imparare",
"japanese": "Kana giapponese",
"english": "Alfabeto inglese",
"uyghur": "Alfabeto uiguro",
"esperanto": "Alfabeto esperanto",
"loading": "Caricamento...",
"loadFailed": "Caricamento fallito, riprova",
"hideLetter": "Nascondi lettera",
"showLetter": "Mostra lettera",
"hideIPA": "Nascondi IPA",
"showIPA": "Mostra IPA",
"roman": "Romanizzazione",
"letter": "Lettera",
"random": "Modalità casuale",
"randomNext": "Successivo casuale"
},
"folders": {
"title": "Cartelle",
"subtitle": "Gestisci le tue collezioni",
"newFolder": "Nuova cartella",
"creating": "Creazione...",
"noFoldersYet": "Nessuna cartella ancora",
"folderInfo": "ID: {id} • {totalPairs} coppie",
"enterFolderName": "Inserisci nome cartella:",
"confirmDelete": "Digita \"{name}\" per eliminare:"
},
"folder_id": {
"unauthorized": "Non sei il proprietario di questa cartella",
"back": "Indietro",
"textPairs": "Coppie di testi",
"itemsCount": "{count} elementi",
"memorize": "Memorizza",
"loadingTextPairs": "Caricamento coppie di testi...",
"noTextPairs": "Nessuna coppia di testi in questa cartella",
"addNewTextPair": "Aggiungi nuova coppia di testi",
"add": "Aggiungi",
"updateTextPair": "Aggiorna coppia di testi",
"update": "Aggiorna",
"text1": "Testo 1",
"text2": "Testo 2",
"language1": "Lingua 1",
"language2": "Lingua 2",
"enterLanguageName": "Inserisci il nome della lingua",
"edit": "Modifica",
"delete": "Elimina",
"permissionDenied": "Non hai il permesso di eseguire questa azione",
"error": {
"update": "Non hai il permesso di aggiornare questo elemento.",
"delete": "Non hai il permesso di eliminare questo elemento.",
"add": "Non hai il permesso di aggiungere elementi a questa cartella.",
"rename": "Non hai il permesso di rinominare questa cartella.",
"deleteFolder": "Non hai il permesso di eliminare questa cartella."
}
},
"home": {
"title": "Impara le lingue",
"description": "Questo è un sito web molto utile che ti aiuta a imparare quasi tutte le lingue del mondo, incluse quelle costruite.",
"explore": "Esplora",
"fortune": {
"quote": "Stay hungry, stay foolish.",
"author": "— Steve Jobs"
},
"translator": {
"name": "Traduttore",
"description": "Traduci in qualsiasi lingua e annota con l'alfabeto fonetico internazionale (IPA)"
},
"textSpeaker": {
"name": "Lettore di testo",
"description": "Riconosce e legge il testo ad alta voce, supporta la riproduzione in loop e la regolazione della velocità"
},
"srtPlayer": {
"name": "Lettore video SRT",
"description": "Riproduci video frase per frase basandoti su file di sottotitoli SRT per imitare la pronuncia dei madrelingua"
},
"alphabet": {
"name": "Alfabeto",
"description": "Inizia a imparare una nuova lingua dall'alfabeto"
},
"memorize": {
"name": "Memorizza",
"description": "Lingua A verso lingua B, lingua B verso lingua A, supporta dettatura"
},
"dictionary": {
"name": "Dizionario",
"description": "Cerca parole e frasi con definizioni dettagliate ed esempi"
},
"moreFeatures": {
"name": "Altre funzionalità",
"description": "In sviluppo, rimani sintonizzato"
}
},
"auth": {
"title": "Autenticazione",
"signIn": "Accedi",
"signUp": "Registrati",
"email": "Email",
"password": "Password",
"confirmPassword": "Conferma password",
"name": "Nome",
"signInButton": "Accedi",
"signUpButton": "Registrati",
"noAccount": "Non hai un account?",
"hasAccount": "Hai già un account?",
"signInWithGitHub": "Accedi con GitHub",
"signUpWithGitHub": "Registrati con GitHub",
"invalidEmail": "Inserisci un indirizzo email valido",
"passwordTooShort": "La password deve essere di almeno 8 caratteri",
"passwordsNotMatch": "Le password non corrispondono",
"nameRequired": "Inserisci il tuo nome",
"emailRequired": "Inserisci la tua email",
"passwordRequired": "Inserisci la tua password",
"confirmPasswordRequired": "Conferma la tua password",
"loading": "Caricamento..."
},
"memorize": {
"folder_selector": {
"selectFolder": "Seleziona una cartella",
"noFolders": "Nessuna cartella trovata",
"folderInfo": "{id}. {name} ({count})"
},
"memorize": {
"answer": "Risposta",
"next": "Successivo",
"reverse": "Inverti",
"dictation": "Dettatura",
"noTextPairs": "Nessuna coppia di testi disponibile",
"disorder": "Disordine",
"previous": "Precedente"
},
"page": {
"unauthorized": "Non sei autorizzato ad accedere a questa cartella"
}
},
"navbar": {
"title": "learn-languages",
"sourceCode": "GitHub",
"sign_in": "Accedi",
"profile": "Profilo",
"folders": "Cartelle"
},
"profile": {
"myProfile": "Il mio profilo",
"email": "Email: {email}",
"logout": "Esci"
},
"srt_player": {
"uploadVideo": "Carica video",
"uploadSubtitle": "Carica sottotitoli",
"pause": "Pausa",
"play": "Riproduci",
"previous": "Precedente",
"next": "Successivo",
"restart": "Riavvia",
"autoPause": "Pausa automatica ({enabled})",
"uploadVideoAndSubtitle": "Carica i file video e sottotitoli",
"uploadVideoFile": "Carica un file video",
"uploadSubtitleFile": "Carica un file di sottotitoli",
"processingSubtitle": "Elaborazione file sottotitoli...",
"needBothFiles": "Sono richiesti sia i file video che i sottotitoli per iniziare l'apprendimento",
"videoFile": "File video",
"subtitleFile": "File sottotitoli",
"uploaded": "Caricato",
"notUploaded": "Non caricato",
"upload": "Carica",
"autoPauseStatus": "Pausa automatica: {enabled}",
"on": "Attivo",
"off": "Disattivo",
"videoUploadFailed": "Caricamento video fallito",
"subtitleUploadFailed": "Caricamento sottotitoli fallito"
},
"text_speaker": {
"generateIPA": "Genera IPA",
"viewSavedItems": "Visualizza elementi salvati",
"confirmDeleteAll": "Sei sicuro di voler eliminare tutto? (S/N)"
},
"translator": {
"detectLanguage": "rileva lingua",
"generateIPA": "genera ipa",
"translateInto": "traduci in",
"chinese": "Cinese",
"english": "Inglese",
"french": "Francese",
"german": "Tedesco",
"italian": "Italiano",
"japanese": "Giapponese",
"korean": "Coreano",
"portuguese": "Portoghese",
"russian": "Russo",
"spanish": "Spagnolo",
"other": "Altro",
"translating": "traduzione...",
"translate": "traduci",
"inputLanguage": "Inserisci una lingua.",
"history": "Cronologia",
"enterLanguage": "Inserisci lingua",
"add_to_folder": {
"notAuthenticated": "Non sei autenticato",
"chooseFolder": "Scegli una cartella a cui aggiungere",
"noFolders": "Nessuna cartella trovata",
"folderInfo": "{id}. {name}",
"close": "Chiudi",
"success": "Coppia di testi aggiunta alla cartella",
"error": "Impossibile aggiungere la coppia di testi alla cartella"
},
"autoSave": "Salvataggio automatico"
},
"dictionary": {
"title": "Dizionario",
"description": "Cerca parole e frasi con definizioni dettagliate ed esempi",
"searchPlaceholder": "Inserisci una parola o frase da cercare...",
"searching": "Ricerca...",
"search": "Cerca",
"languageSettings": "Impostazioni lingua",
"queryLanguage": "Lingua di interrogazione",
"queryLanguageHint": "Quale è la lingua della parola/frase che vuoi cercare",
"definitionLanguage": "Lingua di definizione",
"definitionLanguageHint": "In quale lingua vuoi vedere le definizioni",
"otherLanguagePlaceholder": "Oppure inserisci un'altra lingua...",
"currentSettings": "Impostazioni attuali: Interrogazione {queryLang}, Definizione {definitionLang}",
"relookup": "Ricerca di nuovo",
"saveToFolder": "Salva nella cartella",
"loading": "Caricamento...",
"noResults": "Nessun risultato trovato",
"tryOtherWords": "Prova altre parole o frasi",
"welcomeTitle": "Benvenuto nel dizionario",
"welcomeHint": "Inserisci una parola o frase nella casella di ricerca sopra per iniziare",
"lookupFailed": "Ricerca fallita, riprova più tardi",
"relookupSuccess": "Ricerca ripetuta con successo",
"relookupFailed": "Nuova ricerca del dizionario fallita",
"pleaseLogin": "Accedi prima",
"pleaseCreateFolder": "Crea prima una cartella",
"savedToFolder": "Salvato nella cartella: {folderName}",
"saveFailed": "Salvataggio fallito, riprova più tardi"
},
"user_profile": {
"anonymous": "Anonimo",
"email": "Email",
"verified": "Verificato",
"unverified": "Non verificato",
"accountInfo": "Informazioni account",
"userId": "ID utente",
"username": "Nome utente",
"displayName": "Nome visualizzato",
"notSet": "Non impostato",
"memberSince": "Membro dal",
"folders": {
"title": "Cartelle",
"noFolders": "Nessuna cartella ancora",
"folderName": "Nome cartella",
"totalPairs": "Numero di coppie",
"createdAt": "Creato il",
"actions": "Azioni",
"view": "Visualizza"
}
}
}

258
messages/ja-JP.json Normal file
View File

@@ -0,0 +1,258 @@
{
"alphabet": {
"chooseCharacters": "学習したい文字を選択してください",
"japanese": "日本語仮名",
"english": "英語アルファベット",
"uyghur": "ウイグル文字",
"esperanto": "エスペラント文字",
"loading": "読み込み中...",
"loadFailed": "読み込みに失敗しました。もう一度お試しください",
"hideLetter": "文字を非表示",
"showLetter": "文字を表示",
"hideIPA": "IPAを非表示",
"showIPA": "IPAを表示",
"roman": "ローマ字",
"letter": "文字",
"random": "ランダムモード",
"randomNext": "ランダムで次へ"
},
"folders": {
"title": "フォルダー",
"subtitle": "コレクションを管理",
"newFolder": "新規フォルダー",
"creating": "作成中...",
"noFoldersYet": "フォルダーがありません",
"folderInfo": "ID: {id} • {totalPairs}組",
"enterFolderName": "フォルダー名を入力:",
"confirmDelete": "削除するには「{name}」と入力してください:"
},
"folder_id": {
"unauthorized": "あなたはこのフォルダーの所有者ではありません",
"back": "戻る",
"textPairs": "テキストペア",
"itemsCount": "{count}項目",
"memorize": "暗記",
"loadingTextPairs": "テキストペアを読み込み中...",
"noTextPairs": "このフォルダーにはテキストペアがありません",
"addNewTextPair": "新しいテキストペアを追加",
"add": "追加",
"updateTextPair": "テキストペアを更新",
"update": "更新",
"text1": "テキスト1",
"text2": "テキスト2",
"language1": "言語1",
"language2": "言語2",
"enterLanguageName": "言語名を入力してください",
"edit": "編集",
"delete": "削除",
"permissionDenied": "この操作を実行する権限がありません",
"error": {
"update": "この項目を更新する権限がありません。",
"delete": "この項目を削除する権限がありません。",
"add": "このフォルダーに項目を追加する権限がありません。",
"rename": "このフォルダー名を変更する権限がありません。",
"deleteFolder": "このフォルダーを削除する権限がありません。"
}
},
"home": {
"title": "言語を学ぶ",
"description": "これは、人工言語を含む世界中のほぼすべての言語を学ぶのに役立つ非常に便利なウェブサイトです。",
"explore": "探索",
"fortune": {
"quote": "Stay hungry, stay foolish.",
"author": "— スティーブ・ジョブズ"
},
"translator": {
"name": "翻訳",
"description": "任意の言語に翻訳し、国際音声記号IPAで注釈を付けます"
},
"textSpeaker": {
"name": "テキストスピーカー",
"description": "テキストを認識して音読します。ループ再生と速度調整をサポート"
},
"srtPlayer": {
"name": "SRTビデオプレーヤー",
"description": "SRT字幕ファイルに基づいてビデオを文ごとに再生し、ネイティブスピーカーの発音を模倣します"
},
"alphabet": {
"name": "アルファベット",
"description": "アルファベットから新しい言語の学習を始めましょう"
},
"memorize": {
"name": "暗記",
"description": "言語Aから言語B、言語Bから言語A、ディクテーションをサポート"
},
"dictionary": {
"name": "辞書",
"description": "単語やフレーズを調べ、詳細な定義と例を表示"
},
"moreFeatures": {
"name": "その他の機能",
"description": "開発中です。お楽しみに"
}
},
"auth": {
"title": "認証",
"signIn": "ログイン",
"signUp": "新規登録",
"email": "メールアドレス",
"password": "パスワード",
"confirmPassword": "パスワード(確認)",
"name": "名前",
"signInButton": "ログイン",
"signUpButton": "新規登録",
"noAccount": "アカウントをお持ちでないですか?",
"hasAccount": "すでにアカウントをお持ちですか?",
"signInWithGitHub": "GitHubでログイン",
"signUpWithGitHub": "GitHubで新規登録",
"invalidEmail": "有効なメールアドレスを入力してください",
"passwordTooShort": "パスワードは8文字以上である必要があります",
"passwordsNotMatch": "パスワードが一致しません",
"nameRequired": "名前を入力してください",
"emailRequired": "メールアドレスを入力してください",
"passwordRequired": "パスワードを入力してください",
"confirmPasswordRequired": "パスワード(確認)を入力してください",
"loading": "読み込み中..."
},
"memorize": {
"folder_selector": {
"selectFolder": "フォルダーを選択",
"noFolders": "フォルダーが見つかりません",
"folderInfo": "{id}. {name} ({count})"
},
"memorize": {
"answer": "回答",
"next": "次へ",
"reverse": "逆順",
"dictation": "ディクテーション",
"noTextPairs": "利用可能なテキストペアがありません",
"disorder": "ランダム",
"previous": "前へ"
},
"page": {
"unauthorized": "このフォルダーにアクセスする権限がありません"
}
},
"navbar": {
"title": "learn-languages",
"sourceCode": "GitHub",
"sign_in": "ログイン",
"profile": "プロフィール",
"folders": "フォルダー"
},
"profile": {
"myProfile": "マイプロフィール",
"email": "メールアドレス: {email}",
"logout": "ログアウト"
},
"srt_player": {
"uploadVideo": "ビデオをアップロード",
"uploadSubtitle": "字幕をアップロード",
"pause": "一時停止",
"play": "再生",
"previous": "前へ",
"next": "次へ",
"restart": "最初から",
"autoPause": "自動一時停止 ({enabled})",
"uploadVideoAndSubtitle": "ビデオと字幕ファイルをアップロードしてください",
"uploadVideoFile": "ビデオファイルをアップロードしてください",
"uploadSubtitleFile": "字幕ファイルをアップロードしてください",
"processingSubtitle": "字幕ファイルを処理中...",
"needBothFiles": "学習を開始するにはビデオと字幕ファイルの両方が必要です",
"videoFile": "ビデオファイル",
"subtitleFile": "字幕ファイル",
"uploaded": "アップロード済み",
"notUploaded": "未アップロード",
"upload": "アップロード",
"autoPauseStatus": "自動一時停止: {enabled}",
"on": "オン",
"off": "オフ",
"videoUploadFailed": "ビデオのアップロードに失敗しました",
"subtitleUploadFailed": "字幕のアップロードに失敗しました"
},
"text_speaker": {
"generateIPA": "IPAを生成",
"viewSavedItems": "保存済みアイテムを表示",
"confirmDeleteAll": "本当にすべて削除しますか? (Y/N)"
},
"translator": {
"detectLanguage": "言語を検出",
"generateIPA": "IPAを生成",
"translateInto": "翻訳",
"chinese": "中国語",
"english": "英語",
"french": "フランス語",
"german": "ドイツ語",
"italian": "イタリア語",
"japanese": "日本語",
"korean": "韓国語",
"portuguese": "ポルトガル語",
"russian": "ロシア語",
"spanish": "スペイン語",
"other": "その他",
"translating": "翻訳中...",
"translate": "翻訳",
"inputLanguage": "言語を入力してください。",
"history": "履歴",
"enterLanguage": "言語を入力",
"add_to_folder": {
"notAuthenticated": "認証されていません",
"chooseFolder": "追加するフォルダーを選択",
"noFolders": "フォルダーが見つかりません",
"folderInfo": "{id}. {name}",
"close": "閉じる",
"success": "テキストペアをフォルダーに追加しました",
"error": "テキストペアの追加に失敗しました"
},
"autoSave": "自動保存"
},
"dictionary": {
"title": "辞書",
"description": "詳細な定義と例で単語やフレーズを検索",
"searchPlaceholder": "検索する単語やフレーズを入力...",
"searching": "検索中...",
"search": "検索",
"languageSettings": "言語設定",
"queryLanguage": "クエリ言語",
"queryLanguageHint": "検索する単語/フレーズの言語",
"definitionLanguage": "定義言語",
"definitionLanguageHint": "定義を表示する言語",
"otherLanguagePlaceholder": "または他の言語を入力...",
"currentSettings": "現在の設定:クエリ {queryLang}、定義 {definitionLang}",
"relookup": "再検索",
"saveToFolder": "フォルダに保存",
"loading": "読み込み中...",
"noResults": "結果が見つかりません",
"tryOtherWords": "他の単語やフレーズを試してください",
"welcomeTitle": "辞書へようこそ",
"welcomeHint": "上の検索ボックスに単語やフレーズを入力して検索を開始",
"lookupFailed": "検索に失敗しました。後でもう一度お試しください",
"relookupSuccess": "再検索しました",
"relookupFailed": "辞書の再検索に失敗しました",
"pleaseLogin": "まずログインしてください",
"pleaseCreateFolder": "まずフォルダを作成してください",
"savedToFolder": "フォルダに保存しました:{folderName}",
"saveFailed": "保存に失敗しました。後でもう一度お試しください"
},
"user_profile": {
"anonymous": "匿名",
"email": "メールアドレス",
"verified": "認証済み",
"unverified": "未認証",
"accountInfo": "アカウント情報",
"userId": "ユーザーID",
"username": "ユーザー名",
"displayName": "表示名",
"notSet": "未設定",
"memberSince": "登録日",
"folders": {
"title": "フォルダー",
"noFolders": "フォルダーがありません",
"folderName": "フォルダー名",
"totalPairs": "テキストペア数",
"createdAt": "作成日",
"actions": "操作",
"view": "表示"
}
}
}

258
messages/ko-KR.json Normal file
View File

@@ -0,0 +1,258 @@
{
"alphabet": {
"chooseCharacters": "학습할 문자를 선택하세요",
"japanese": "일본어 가나",
"english": "영문 알파벳",
"uyghur": "위구르 문자",
"esperanto": "에스페란토 문자",
"loading": "로딩 중...",
"loadFailed": "로딩 실패, 다시 시도해 주세요",
"hideLetter": "문자 숨기기",
"showLetter": "문자 표시",
"hideIPA": "IPA 숨기기",
"showIPA": "IPA 표시",
"roman": "로마자 표기",
"letter": "문자",
"random": "무작위 모드",
"randomNext": "무작위 다음"
},
"folders": {
"title": "폴더",
"subtitle": "컬렉션 관리",
"newFolder": "새 폴더",
"creating": "생성 중...",
"noFoldersYet": "폴더가 없습니다",
"folderInfo": "ID: {id} • {totalPairs}쌍",
"enterFolderName": "폴더 이름 입력:",
"confirmDelete": "삭제하려면 \"{name}\"을(를) 입력하세요:"
},
"folder_id": {
"unauthorized": "이 폴더의 소유자가 아닙니다",
"back": "뒤로",
"textPairs": "텍스트 쌍",
"itemsCount": "{count}개 항목",
"memorize": "암기",
"loadingTextPairs": "텍스트 쌍 로딩 중...",
"noTextPairs": "이 폴더에 텍스트 쌍이 없습니다",
"addNewTextPair": "새 텍스트 쌍 추가",
"add": "추가",
"updateTextPair": "텍스트 쌍 업데이트",
"update": "업데이트",
"text1": "텍스트 1",
"text2": "텍스트 2",
"language1": "언어 1",
"language2": "언어 2",
"enterLanguageName": "언어 이름을 입력하세요",
"edit": "편집",
"delete": "삭제",
"permissionDenied": "이 작업을 수행할 권한이 없습니다",
"error": {
"update": "이 항목을 업데이트할 권한이 없습니다.",
"delete": "이 항목을 삭제할 권한이 없습니다.",
"add": "이 폴더에 항목을 추가할 권한이 없습니다.",
"rename": "이 폴더 이름을 변경할 권한이 없습니다.",
"deleteFolder": "이 폴더를 삭제할 권한이 없습니다."
}
},
"home": {
"title": "언어 학습",
"description": "인공 언어를 포함하여 세상의 거의 모든 언어를 배우는 데 도움이 되는 매우 유용한 웹사이트입니다.",
"explore": "탐색",
"fortune": {
"quote": "Stay hungry, stay foolish.",
"author": "— 스티브 잡스"
},
"translator": {
"name": "번역기",
"description": "모든 언어로 번역하고 국제 음성 기호(IPA)로 주석 추가"
},
"textSpeaker": {
"name": "텍스트 스피커",
"description": "텍스트를 인식하고 읽어줍니다. 반복 재생 및 속도 조정 지원"
},
"srtPlayer": {
"name": "SRT 비디오 플레이어",
"description": "SRT 자막 파일을 기반으로 문장별로 비디오를 재생하여 원어민 발음 모방"
},
"alphabet": {
"name": "알파벳",
"description": "알파벳부터 새로운 언어 학습 시작"
},
"memorize": {
"name": "암기",
"description": "언어 A에서 언어 B로, 언어 B에서 언어 A로, 받아쓰기 지원"
},
"dictionary": {
"name": "사전",
"description": "단어와 구문을 조회하고 자세한 정의와 예제 제공"
},
"moreFeatures": {
"name": "더 많은 기능",
"description": "개발 중, 기대해 주세요"
}
},
"auth": {
"title": "인증",
"signIn": "로그인",
"signUp": "회원가입",
"email": "이메일",
"password": "비밀번호",
"confirmPassword": "비밀번호 확인",
"name": "이름",
"signInButton": "로그인",
"signUpButton": "회원가입",
"noAccount": "계정이 없으신가요?",
"hasAccount": "이미 계정이 있으신가요?",
"signInWithGitHub": "GitHub로 로그인",
"signUpWithGitHub": "GitHub로 회원가입",
"invalidEmail": "유효한 이메일 주소를 입력하세요",
"passwordTooShort": "비밀번호는 최소 8자 이상이어야 합니다",
"passwordsNotMatch": "비밀번호가 일치하지 않습니다",
"nameRequired": "이름을 입력하세요",
"emailRequired": "이메일을 입력하세요",
"passwordRequired": "비밀번호를 입력하세요",
"confirmPasswordRequired": "비밀번호 확인을 입력하세요",
"loading": "로딩 중..."
},
"memorize": {
"folder_selector": {
"selectFolder": "폴더 선택",
"noFolders": "폴더를 찾을 수 없습니다",
"folderInfo": "{id}. {name} ({count})"
},
"memorize": {
"answer": "정답",
"next": "다음",
"reverse": "반대",
"dictation": "받아쓰기",
"noTextPairs": "사용 가능한 텍스트 쌍이 없습니다",
"disorder": "무작위",
"previous": "이전"
},
"page": {
"unauthorized": "이 폴더에 액세스할 권한이 없습니다"
}
},
"navbar": {
"title": "learn-languages",
"sourceCode": "GitHub",
"sign_in": "로그인",
"profile": "프로필",
"folders": "폴더"
},
"profile": {
"myProfile": "내 프로필",
"email": "이메일: {email}",
"logout": "로그아웃"
},
"srt_player": {
"uploadVideo": "비디오 업로드",
"uploadSubtitle": "자막 업로드",
"pause": "일시정지",
"play": "재생",
"previous": "이전",
"next": "다음",
"restart": "처음부터",
"autoPause": "자동 일시정지 ({enabled})",
"uploadVideoAndSubtitle": "비디오와 자막 파일을 업로드하세요",
"uploadVideoFile": "비디오 파일을 업로드하세요",
"uploadSubtitleFile": "자막 파일을 업로드하세요",
"processingSubtitle": "자막 파일 처리 중...",
"needBothFiles": "학습을 시작하려면 비디오와 자막 파일이 모두 필요합니다",
"videoFile": "비디오 파일",
"subtitleFile": "자막 파일",
"uploaded": "업로드됨",
"notUploaded": "업로드되지 않음",
"upload": "업로드",
"autoPauseStatus": "자동 일시정지: {enabled}",
"on": "켜기",
"off": "끄기",
"videoUploadFailed": "비디오 업로드 실패",
"subtitleUploadFailed": "자막 업로드 실패"
},
"text_speaker": {
"generateIPA": "IPA 생성",
"viewSavedItems": "저장된 항목 보기",
"confirmDeleteAll": "정말 모두 삭제하시겠습니까? (Y/N)"
},
"translator": {
"detectLanguage": "언어 감지",
"generateIPA": "IPA 생성",
"translateInto": "번역",
"chinese": "중국어",
"english": "영어",
"french": "프랑스어",
"german": "독일어",
"italian": "이탈리아어",
"japanese": "일본어",
"korean": "한국어",
"portuguese": "포르투갈어",
"russian": "러시아어",
"spanish": "스페인어",
"other": "기타",
"translating": "번역 중...",
"translate": "번역",
"inputLanguage": "언어를 입력하세요.",
"history": "기록",
"enterLanguage": "언어 입력",
"add_to_folder": {
"notAuthenticated": "인증되지 않았습니다",
"chooseFolder": "추가할 폴더 선택",
"noFolders": "폴더를 찾을 수 없습니다",
"folderInfo": "{id}. {name}",
"close": "닫기",
"success": "텍스트 쌍을 폴더에 추가했습니다",
"error": "텍스트 쌍 추가 실패"
},
"autoSave": "자동 저장"
},
"dictionary": {
"title": "사전",
"description": "상세한 정의와 예제로 단어 및 구문 검색",
"searchPlaceholder": "검색할 단어나 구문을 입력하세요...",
"searching": "검색 중...",
"search": "검색",
"languageSettings": "언어 설정",
"queryLanguage": "쿼리 언어",
"queryLanguageHint": "검색하려는 단어/구문의 언어",
"definitionLanguage": "정의 언어",
"definitionLanguageHint": "정의를 표시할 언어",
"otherLanguagePlaceholder": "또는 다른 언어를 입력하세요...",
"currentSettings": "현재 설정: 쿼리 {queryLang}, 정의 {definitionLang}",
"relookup": "재검색",
"saveToFolder": "폴더에 저장",
"loading": "로드 중...",
"noResults": "결과를 찾을 수 없습니다",
"tryOtherWords": "다른 단어나 구문을 시도하세요",
"welcomeTitle": "사전에 오신 것을 환영합니다",
"welcomeHint": "위 검색 상자에 단어나 구문을 입력하여 검색을 시작하세요",
"lookupFailed": "검색 실패, 나중에 다시 시도하세요",
"relookupSuccess": "재검색했습니다",
"relookupFailed": "사전 재검색 실패",
"pleaseLogin": "먼저 로그인하세요",
"pleaseCreateFolder": "먼저 폴더를 만드세요",
"savedToFolder": "폴더에 저장됨: {folderName}",
"saveFailed": "저장 실패, 나중에 다시 시도하세요"
},
"user_profile": {
"anonymous": "익명",
"email": "이메일",
"verified": "인증됨",
"unverified": "미인증",
"accountInfo": "계정 정보",
"userId": "사용자 ID",
"username": "사용자명",
"displayName": "표시 이름",
"notSet": "설정되지 않음",
"memberSince": "가입일",
"folders": {
"title": "폴더",
"noFolders": "폴더가 없습니다",
"folderName": "폴더 이름",
"totalPairs": "텍스트 쌍 수",
"createdAt": "생성일",
"actions": "작업",
"view": "보기"
}
}
}

258
messages/ug-CN.json Normal file
View File

@@ -0,0 +1,258 @@
{
"alphabet": {
"chooseCharacters": "ئۆگىنەرلىك ھەرپلەرنى تاللاڭ",
"japanese": "ياپونىيە كانا",
"english": "ئىنگلىز ئېلىپبې",
"uyghur": "ئۇيغۇر ئېلىپبېسى",
"esperanto": "ئېسپېرانتو ئېلىپبېسى",
"loading": "چىقىرىۋېتىلىۋاتىدۇ...",
"loadFailed": "چىقىرىش مەغلۇب بولدى، قايتا سىناڭ",
"hideLetter": "ھەرپنى يوشۇرۇش",
"showLetter": "ھەرپنى كۆرسىتىش",
"hideIPA": "IPA نى يوشۇرۇش",
"showIPA": "IPA نى كۆرسىتىش",
"roman": "روماللاشتۇرۇش",
"letter": "ھەرپ",
"random": "ئىختىيارىي ھالەت",
"randomNext": "ئىختىيارىي كېيىنكى"
},
"folders": {
"title": "قىسقۇچلار",
"subtitle": "توپلىمىڭىزنى باشقۇرۇڭ",
"newFolder": "يېڭى قىسقۇچ",
"creating": "قۇرۇۋاتىدۇ...",
"noFoldersYet": "قىسقۇچ يوق",
"folderInfo": "كود: {id} • {totalPairs} جۈپ",
"enterFolderName": "قىسقۇچ نامىنى كىرگۈزۈڭ:",
"confirmDelete": "ئۆچۈرۈش ئۈچۈن «{name}» نى كىرگۈزۈڭ:"
},
"folder_id": {
"unauthorized": "سىز بۇ قىسقۇچنىڭ ئىگىسى ئەمەس",
"back": "كەينىگە",
"textPairs": "تېكىست جۈپلىرى",
"itemsCount": "{count} تۈر",
"memorize": "ئەستە ساقلاش",
"loadingTextPairs": "تېكىست جۈپلىرى چىقىرىۋېتىلىۋاتىدۇ...",
"noTextPairs": "بۇ قىسقۇچتا تېكىست جۈپى يوق",
"addNewTextPair": "يېڭى تېكىست جۈپى قوشۇڭ",
"add": "قوشۇش",
"updateTextPair": "تېكىست جۈپىنى يېڭىلاڭ",
"update": "يېڭىلاش",
"text1": "تېكىست 1",
"text2": "تېكىست 2",
"language1": "تىل 1",
"language2": "تىل 2",
"enterLanguageName": "تىل نامىنى كىرگۈزۈڭ",
"edit": "تەھرىرلەش",
"delete": "ئۆچۈرۈش",
"permissionDenied": "بۇ مەشغۇلاتنى ئىجرا قىلىش ھوقۇقىڭىز يوق",
"error": {
"update": "بۇ تۈرنى يېڭىلاش ھوقۇقىڭىز يوق.",
"delete": "بۇ تۈرنى ئۆچۈرۈش ھوقۇقىڭىز يوق.",
"add": "بۇ قىسقۇچقا تۈر قوشۇش ھوقۇقىڭىز يوق.",
"rename": "بۇ قىسقۇچنىڭ نامىنى ئۆزگەرتىش ھوقۇقىڭىز يوق.",
"deleteFolder": "بۇ قىسقۇچنى ئۆچۈرۈش ھوقۇقىڭىز يوق."
}
},
"home": {
"title": "تىل ئۆگىنىڭ",
"description": "بۇ سىزنى دۇنيادىكى ھەممە تىلنى، جۈملىدىن سۈنئىي تىللارنىمۇ ئۆگىنىشىڭىزغا ياردەم بېرىدىغان ناھايىتى پايدىلىق تور بېكەت.",
"explore": "ئىزدىنىش",
"fortune": {
"quote": "Stay hungry, stay foolish.",
"author": "— ستىۋ جوۋبس"
},
"translator": {
"name": "تەرجىمە",
"description": "خالىغان تىلغا تەرجىمە قىلىپ خەلقئارالىق فونېتىك ئېلىپبې (IPA) بىلەن ئىزاھاتلاش"
},
"textSpeaker": {
"name": "تېكىست ئوقۇغۇچى",
"description": "تېكىستنى پەرقلەندۈرۈپ ئوقىيدۇ، دەۋرىي ئوقۇش ۋە سۈرئەت تەڭشەشنى قوللايدۇ"
},
"srtPlayer": {
"name": "SRT سىن ئوپىراتورى",
"description": "SRT خەت ئاستى فايلى ئاساسىدا سىننى جۈملە-جۈملە قويۇپ، يەرلىك ئىخچام ئاۋازنى ئىمتىلايدۇ"
},
"alphabet": {
"name": "ئېلىپبې",
"description": "ئېلىپبېدىن يېڭى تىل ئۆگىنىشنى باشلاڭ"
},
"memorize": {
"name": "ئەستە ساقلاش",
"description": "تىل A دىن تىل غا، تىل B دىن تىل A غا، دىكتات قوللايدۇ"
},
"dictionary": {
"name": "لۇغەت",
"description": "سۆز ۋە سۆزنى ئىزدەپ، تەپسىلىي ئىزاھات ۋە مىساللار بىلەن تەمىنلەيدۇ"
},
"moreFeatures": {
"name": "تېخىمۇ كۆپ ئىقتىدار",
"description": "ئىشلەۋاتىدۇ، كۈتكۈن بولۇڭ"
}
},
"auth": {
"title": "دەلىللەش",
"signIn": "كىرىش",
"signUp": "تىزىملىتىش",
"email": "ئېلخەت",
"password": "ئىم",
"confirmPassword": "ئىمنى جەزملەش",
"name": "نام",
"signInButton": "كىرىش",
"signUpButton": "تىزىملىتىش",
"noAccount": "ھېساباتىڭىز يوقمۇ؟",
"hasAccount": "ھېساباتىڭىز بارمۇ؟",
"signInWithGitHub": "GitHub بىلەن كىرىڭ",
"signUpWithGitHub": "GitHub بىلەن تىزىملىتىڭ",
"invalidEmail": "ئىناۋەتلىك ئېلخەت ئادرېسى كىرگۈزۈڭ",
"passwordTooShort": "ئىم كەم دېگەندە 8 ھەرپتىن تۇرۇشى كېرەك",
"passwordsNotMatch": "ئىم ماس كەلمەيدۇ",
"nameRequired": "نامىڭىزنى كىرگۈزۈڭ",
"emailRequired": "ئېلخىتىڭىزنى كىرگۈزۈڭ",
"passwordRequired": "ئىمىڭىزنى كىرگۈزۈڭ",
"confirmPasswordRequired": "ئىمىڭىزنى جەزملەڭ",
"loading": "چىقىرىۋېتىلىۋاتىدۇ..."
},
"memorize": {
"folder_selector": {
"selectFolder": "قىسقۇچ تاللاڭ",
"noFolders": "قىسقۇچ تېپىلمىدى",
"folderInfo": "{id}. {name} ({count})"
},
"memorize": {
"answer": "جاۋاب",
"next": "كېيىنكى",
"reverse": "تەتۈر",
"dictation": "دىكتات",
"noTextPairs": "ئىشلەتكىلى بولىدىغان تېكىست جۈپى يوق",
"disorder": "بەت ئارلاش",
"previous": "ئىلگىرىكى"
},
"page": {
"unauthorized": "بۇ قىسقۇچنى زىيارەت قىلىشقا ھوقۇقىڭىز يوق"
}
},
"navbar": {
"title": "تىل ئۆگىنىش",
"sourceCode": "GitHub",
"sign_in": "كىرىش",
"profile": "پروفىل",
"folders": "قىسقۇچلار"
},
"profile": {
"myProfile": "مېنىڭ پروفىلىم",
"email": "ئېلخەت: {email}",
"logout": "چىقىش"
},
"srt_player": {
"uploadVideo": "سىن يۈكلەڭ",
"uploadSubtitle": "خەت ئاستى يۈكلەڭ",
"pause": "ۋاقىتلىق توختىتىش",
"play": "قويۇش",
"previous": "ئىلگىرىكى",
"next": "كېيىنكى",
"restart": "قايتا باشلاش",
"autoPause": "ئاپتوماتىك توختىتىش ({enabled})",
"uploadVideoAndSubtitle": "سىن ھەم خەت ئاستى فايلىنى يۈكلەڭ",
"uploadVideoFile": "سىن فايلى يۈكلەڭ",
"uploadSubtitleFile": "خەت ئاستى فايلى يۈكلەڭ",
"processingSubtitle": "خەت ئاستى فايلى بىر تەرەپ قىلىۋاتىدۇ...",
"needBothFiles": "ئۆگىنىشنى باشلاش ئۈچۈن سىن ھەم خەت ئاستى فايلىنىڭ ھەممىسى لازىم",
"videoFile": "سىن فايلى",
"subtitleFile": "خەت ئاستى فايلى",
"uploaded": "يۈكلەندى",
"notUploaded": "يۈكلەنمىدى",
"upload": "يۈكلەش",
"autoPauseStatus": "ئاپتوماتىك توختىتىش: {enabled}",
"on": "ئوچۇق",
"off": "تاقاق",
"videoUploadFailed": "سىن يۈكلەش مەغلۇب بولدى",
"subtitleUploadFailed": "خەت ئاستى يۈكلەش مەغلۇب بولدى"
},
"text_speaker": {
"generateIPA": "IPA ھاسىل قىلىش",
"viewSavedItems": "ساقلانغان تۈرلەرنى كۆرۈش",
"confirmDeleteAll": "ھەممىنى ئۆچۈرەمسىز؟ (H/Y)"
},
"translator": {
"detectLanguage": "تىل پەرقلەندۈرۈش",
"generateIPA": "IPA ھاسىل قىلىش",
"translateInto": "تەرجىمە قىلىش",
"chinese": "خەنزۇچە",
"english": "ئىنگلىزچە",
"french": "فرانسۇزچە",
"german": "گېرمانچە",
"italian": "ئىتاليانچە",
"japanese": "ياپونچە",
"korean": "كورېيەچە",
"portuguese": "پورتۇگالچە",
"russian": "رۇسچە",
"spanish": "ئىسپانچە",
"other": "باشقا",
"translating": "تەرجىمە قىلىۋاتىدۇ...",
"translate": "تەرجىمە قىلىش",
"inputLanguage": "بىر تىل كىرگۈزۈڭ.",
"history": "تارىخ",
"enterLanguage": "تىل كىرگۈزۈڭ",
"add_to_folder": {
"notAuthenticated": "دەلىتلەنمىدىڭىز",
"chooseFolder": "قوشۇلىدىغان قىسقۇچنى تاللاڭ",
"noFolders": "قىسقۇچ تېپىلمىدى",
"folderInfo": "{id}. {name}",
"close": "تاقاش",
"success": "تېكىست جۈپى قىسقۇچقا قوشۇلدى",
"error": "تېكىست جۈپىنى قىسقۇچقا قوشۇش مەغلۇب بولدى"
},
"autoSave": "ئاپتوماتىك ساقلاش"
},
"dictionary": {
"title": "لۇغەت",
"description": "تەپسىلىي ئىلمىيى ۋە مىساللار بىلەن سۆز ۋە ئىبارە ئىزدەش",
"searchPlaceholder": "ئىزدەيدىغان سۆز ياكى ئىبارە كىرگۈزۈڭ...",
"searching": "ئىزدەۋاتىدۇ...",
"search": "ئىزدە",
"languageSettings": "تىل تەڭشىكى",
"queryLanguage": "سۈرەشتۈرۈش تىلى",
"queryLanguageHint": "ئىزدەمدەكچى بولغان سۆز/ئىبارە قايسى تىلدا",
"definitionLanguage": "ئىلمىيى تىلى",
"definitionLanguageHint": "ئىلمىيىنى قايسى تىلدا كۆرۈشنى ئويلىشىسىز",
"otherLanguagePlaceholder": "ياكى باشقا تىل كىرگۈزۈڭ...",
"currentSettings": "نۆۋەتتىكى تەڭشەك: سۈرەشتۈرۈش {queryLang}، ئىلمىيى {definitionLang}",
"relookup": "قايتا ئىزدە",
"saveToFolder": "قىسقۇچقا ساقلا",
"loading": "يۈكلىۋاتىدۇ...",
"noResults": "نەتىجە تېپىلمىدى",
"tryOtherWords": "باشقا سۆز ياكى ئىبارە سىناڭ",
"welcomeTitle": "لۇغەتكە مەرھەمەت",
"welcomeHint": "ئىزدەشنى باشلاش ئۈچۈن يۇقىرىدىكى ئىزدەش رامكىسىغا سۆز ياكى ئىبارە كىرگۈزۈڭ",
"lookupFailed": "ئىزدەش مەغلۇب بولدى، كېيىنرەك قايتا سىناڭ",
"relookupSuccess": "مۇۋەپپەقىيەتلىك قايتا ئىزدىدى",
"relookupFailed": "لۇغەت قايتا ئىزدىشى مەغلۇب بولدى",
"pleaseLogin": "ئاۋۋال تىزىملىتىڭ",
"pleaseCreateFolder": "ئاۋۋال قىسقۇچ قۇرۇڭ",
"savedToFolder": "قىسقۇچقا ساقلاندى: {folderName}",
"saveFailed": "ساقلاش مەغلۇب بولدى، كېيىنرەك قايتا سىناڭ"
},
"user_profile": {
"anonymous": "ئىسىمسىز",
"email": "ئېلخەت",
"verified": "دەلىللەندى",
"unverified": "دەلىتلەنمىدى",
"accountInfo": "ھېسابات ئۇچۇرى",
"userId": "ئىشلەتكۈچى كودى",
"username": "ئىشلەتكۈچى نامى",
"displayName": "كۆرسىتىلىدىغان نام",
"notSet": "تەڭشەلمىگەن",
"memberSince": "تىزىملاتقان ۋاقىت",
"folders": {
"title": "قىسقۇچلار",
"noFolders": "قىسقۇچ يوق",
"folderName": "قىسقۇچ نامى",
"totalPairs": "تېكىست جۈپ سانى",
"createdAt": "قۇرۇلغان ۋاقىت",
"actions": "مەشغۇلات",
"view": "كۆرۈش"
}
}
}

View File

@@ -22,13 +22,9 @@
"newFolder": "新建文件夹", "newFolder": "新建文件夹",
"creating": "创建中...", "creating": "创建中...",
"noFoldersYet": "还没有文件夹", "noFoldersYet": "还没有文件夹",
"folderInfo": "{id}. {name} ({totalPairs})", "folderInfo": "ID: {id} • {totalPairs} 个文本对",
"enterFolderName": "输入文件夹名称:", "enterFolderName": "输入文件夹名称:",
"confirmDelete": "输入 \"{name}\" 以删除:", "confirmDelete": "输入 \"{name}\" 以删除:"
"createFolderSuccess": "文件夹创建成功",
"deleteFolderSuccess": "文件夹删除成功",
"createFolderError": "创建文件夹失败",
"deleteFolderError": "删除文件夹失败"
}, },
"folder_id": { "folder_id": {
"unauthorized": "您不是此文件夹的所有者", "unauthorized": "您不是此文件夹的所有者",
@@ -44,10 +40,19 @@
"update": "更新", "update": "更新",
"text1": "文本1", "text1": "文本1",
"text2": "文本2", "text2": "文本2",
"locale1": "语言1", "language1": "语言1",
"locale2": "语言2", "language2": "语言2",
"enterLanguageName": "请输入语言名称",
"edit": "编辑", "edit": "编辑",
"delete": "删除" "delete": "删除",
"permissionDenied": "您没有权限执行此操作",
"error": {
"update": "您没有权限更新此项目",
"delete": "您没有权限删除此项目",
"add": "您没有权限向此文件夹添加项目",
"rename": "您没有权限重命名此文件夹",
"deleteFolder": "您没有权限删除此文件夹"
}
}, },
"home": { "home": {
"title": "学语言", "title": "学语言",
@@ -77,15 +82,15 @@
"name": "记忆", "name": "记忆",
"description": "语言A到语言B语言B到语言A支持听写" "description": "语言A到语言B语言B到语言A支持听写"
}, },
"dictionary": {
"name": "词典",
"description": "查询单词和短语,提供详细的释义和例句"
},
"moreFeatures": { "moreFeatures": {
"name": "更多功能", "name": "更多功能",
"description": "开发中,敬请期待" "description": "开发中,敬请期待"
} }
}, },
"login": {
"loading": "加载中...",
"githubLogin": "GitHub登录"
},
"auth": { "auth": {
"title": "登录", "title": "登录",
"signIn": "登录", "signIn": "登录",
@@ -94,6 +99,8 @@
"password": "密码", "password": "密码",
"confirmPassword": "确认密码", "confirmPassword": "确认密码",
"name": "用户名", "name": "用户名",
"username": "用户名",
"emailOrUsername": "邮箱或用户名",
"signInButton": "登录", "signInButton": "登录",
"signUpButton": "注册", "signUpButton": "注册",
"noAccount": "还没有账户?", "noAccount": "还没有账户?",
@@ -103,18 +110,17 @@
"invalidEmail": "请输入有效的邮箱地址", "invalidEmail": "请输入有效的邮箱地址",
"passwordTooShort": "密码至少需要8个字符", "passwordTooShort": "密码至少需要8个字符",
"passwordsNotMatch": "两次输入的密码不匹配", "passwordsNotMatch": "两次输入的密码不匹配",
"signInFailed": "登录失败,请检查您的邮箱和密码",
"signUpFailed": "注册失败,请稍后再试",
"nameRequired": "请输入用户名", "nameRequired": "请输入用户名",
"usernameRequired": "请输入用户名",
"usernameTooShort": "用户名至少需要3个字符",
"usernameInvalid": "用户名只能包含字母、数字和下划线",
"emailRequired": "请输入邮箱", "emailRequired": "请输入邮箱",
"identifierRequired": "请输入邮箱或用户名",
"passwordRequired": "请输入密码", "passwordRequired": "请输入密码",
"confirmPasswordRequired": "请确认密码" "confirmPasswordRequired": "请确认密码",
"loading": "加载中..."
}, },
"memorize": { "memorize": {
"choose": {
"back": "返回",
"choose": "选择"
},
"folder_selector": { "folder_selector": {
"selectFolder": "选择文件夹", "selectFolder": "选择文件夹",
"noFolders": "未找到文件夹", "noFolders": "未找到文件夹",
@@ -155,18 +161,6 @@
"next": "下句", "next": "下句",
"restart": "句首", "restart": "句首",
"autoPause": "自动暂停({enabled})", "autoPause": "自动暂停({enabled})",
"playbackSpeed": "播放速度",
"subtitleSettings": "字幕设置",
"fontSize": "字体大小",
"backgroundColor": "背景颜色",
"textColor": "文字颜色",
"fontFamily": "字体",
"opacity": "透明度",
"position": "位置",
"top": "顶部",
"center": "居中",
"bottom": "底部",
"keyboardShortcuts": "键盘快捷键",
"uploadVideoAndSubtitle": "请上传视频和字幕文件", "uploadVideoAndSubtitle": "请上传视频和字幕文件",
"uploadVideoFile": "请上传视频文件", "uploadVideoFile": "请上传视频文件",
"uploadSubtitleFile": "请上传字幕文件", "uploadSubtitleFile": "请上传字幕文件",
@@ -180,16 +174,7 @@
"on": "开", "on": "开",
"off": "关", "off": "关",
"videoUploadFailed": "视频上传失败", "videoUploadFailed": "视频上传失败",
"subtitleUploadFailed": "字幕上传失败", "subtitleUploadFailed": "字幕上传失败"
"subtitleLoadSuccess": "字幕文件加载成功",
"subtitleLoadFailed": "字幕文件加载失败",
"shortcuts": {
"playPause": "播放/暂停",
"next": "下一句",
"previous": "上一句",
"restart": "句首",
"autoPause": "切换自动暂停"
}
}, },
"text_speaker": { "text_speaker": {
"generateIPA": "生成IPA", "generateIPA": "生成IPA",
@@ -202,7 +187,14 @@
"translateInto": "翻译为", "translateInto": "翻译为",
"chinese": "中文", "chinese": "中文",
"english": "英文", "english": "英文",
"french": "法语",
"german": "德语",
"italian": "意大利语", "italian": "意大利语",
"japanese": "日语",
"korean": "韩语",
"portuguese": "葡萄牙语",
"russian": "俄语",
"spanish": "西班牙语",
"other": "其他", "other": "其他",
"translating": "翻译中...", "translating": "翻译中...",
"translate": "翻译", "translate": "翻译",
@@ -219,5 +211,54 @@
"error": "添加文本对到文件夹失败" "error": "添加文本对到文件夹失败"
}, },
"autoSave": "自动保存" "autoSave": "自动保存"
},
"dictionary": {
"title": "词典",
"description": "查询单词和短语,提供详细的释义和例句",
"searchPlaceholder": "输入要查询的单词或短语...",
"searching": "查询中...",
"search": "查询",
"languageSettings": "语言设置",
"queryLanguage": "查询语言",
"queryLanguageHint": "你要查询的单词/短语是什么语言",
"definitionLanguage": "释义语言",
"definitionLanguageHint": "你希望用什么语言查看释义",
"otherLanguagePlaceholder": "或输入其他语言...",
"currentSettings": "当前设置:查询 {queryLang},释义 {definitionLang}",
"relookup": "重新查询",
"saveToFolder": "保存到文件夹",
"loading": "加载中...",
"noResults": "未找到结果",
"tryOtherWords": "尝试其他单词或短语",
"welcomeTitle": "欢迎使用词典",
"welcomeHint": "在上方搜索框中输入单词或短语开始查询",
"lookupFailed": "查询失败,请稍后重试",
"relookupSuccess": "已重新查询",
"relookupFailed": "词典重新查询失败",
"pleaseLogin": "请先登录",
"pleaseCreateFolder": "请先创建文件夹",
"savedToFolder": "已保存到文件夹:{folderName}",
"saveFailed": "保存失败,请稍后重试"
},
"user_profile": {
"anonymous": "匿名",
"email": "邮箱",
"verified": "已验证",
"unverified": "未验证",
"accountInfo": "账户信息",
"userId": "用户ID",
"username": "用户名",
"displayName": "显示名称",
"notSet": "未设置",
"memberSince": "注册时间",
"folders": {
"title": "文件夹",
"noFolders": "还没有文件夹",
"folderName": "文件夹名称",
"totalPairs": "文本对数量",
"createdAt": "创建时间",
"actions": "操作",
"view": "查看"
}
} }
} }

View File

@@ -2,7 +2,7 @@
"name": "learn-languages", "name": "learn-languages",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"license": "GPL-3.0-only", "license": "AGPL-3.0-only",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "next dev --experimental-https", "dev": "next dev --experimental-https",
@@ -11,36 +11,38 @@
"lint": "eslint" "lint": "eslint"
}, },
"dependencies": { "dependencies": {
"@prisma/adapter-pg": "^7.1.0", "@prisma/adapter-pg": "^7.2.0",
"@prisma/client": "^7.1.0", "@prisma/client": "^7.2.0",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"better-auth": "^1.4.6", "better-auth": "^1.4.10",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dotenv": "^17.2.3", "dotenv": "^17.2.3",
"edge-tts-universal": "^1.3.3", "lucide-react": "^0.562.0",
"lucide-react": "^0.561.0", "next": "16.1.1",
"next": "16.0.10", "next-intl": "^4.7.0",
"next-intl": "^4.5.8",
"pg": "^8.16.3", "pg": "^8.16.3",
"react": "19.2.3", "react": "19.2.3",
"react-dom": "19.2.3", "react-dom": "19.2.3",
"sonner": "^2.0.7", "sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"unstorage": "^1.17.3", "unstorage": "^1.17.3",
"zod": "^4.1.13" "zod": "^4.3.5"
}, },
"devDependencies": { "devDependencies": {
"@better-auth/cli": "^1.4.6", "@better-auth/cli": "^1.4.10",
"@eslint/eslintrc": "^3.3.3", "@eslint/eslintrc": "^3.3.3",
"@tailwindcss/postcss": "^4.1.18", "@tailwindcss/postcss": "^4.1.18",
"@types/node": "^25.0.1", "@types/node": "^25.0.3",
"@types/react": "19.2.7", "@types/react": "19.2.7",
"@types/react-dom": "19.2.3", "@types/react-dom": "19.2.3",
"@typescript-eslint/eslint-plugin": "^8.49.0", "@typescript-eslint/eslint-plugin": "^8.51.0",
"@typescript-eslint/parser": "^8.49.0", "@typescript-eslint/parser": "^8.51.0",
"babel-plugin-react-compiler": "^1.0.0", "babel-plugin-react-compiler": "^1.0.0",
"eslint": "^9.39.1", "eslint": "^9.39.2",
"eslint-config-next": "16.0.10", "eslint-config-next": "16.1.1",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.5",
"prisma": "^7.1.0", "prisma": "^7.2.0",
"tailwindcss": "^4.1.18", "tailwindcss": "^4.1.18",
"typescript": "^5.9.3" "typescript": "^5.9.3"
}, },

1091
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,138 @@
/*
Warnings:
- You are about to drop the column `ipa1` on the `pairs` table. All the data in the column will be lost.
- You are about to drop the column `ipa2` on the `pairs` table. All the data in the column will be lost.
*/
-- AlterTable
-- 重命名并修改类型为 TEXT
ALTER TABLE "pairs"
RENAME COLUMN "locale1" TO "language1";
ALTER TABLE "pairs"
ALTER COLUMN "language1" SET DATA TYPE VARCHAR(20);
ALTER TABLE "pairs"
RENAME COLUMN "locale2" TO "language2";
ALTER TABLE "pairs"
ALTER COLUMN "language2" SET DATA TYPE VARCHAR(20);
-- CreateTable
CREATE TABLE "dictionary_lookups" (
"id" SERIAL NOT NULL,
"user_id" TEXT,
"text" TEXT NOT NULL,
"query_lang" TEXT NOT NULL,
"definition_lang" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"dictionary_word_id" INTEGER,
"dictionary_phrase_id" INTEGER,
CONSTRAINT "dictionary_lookups_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "dictionary_words" (
"id" SERIAL NOT NULL,
"standard_form" TEXT NOT NULL,
"query_lang" TEXT NOT NULL,
"definition_lang" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "dictionary_words_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "dictionary_phrases" (
"id" SERIAL NOT NULL,
"standard_form" TEXT NOT NULL,
"query_lang" TEXT NOT NULL,
"definition_lang" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "dictionary_phrases_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "dictionary_word_entries" (
"id" SERIAL NOT NULL,
"word_id" INTEGER NOT NULL,
"ipa" TEXT NOT NULL,
"definition" TEXT NOT NULL,
"part_of_speech" TEXT NOT NULL,
"example" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "dictionary_word_entries_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "dictionary_phrase_entries" (
"id" SERIAL NOT NULL,
"phrase_id" INTEGER NOT NULL,
"definition" TEXT NOT NULL,
"example" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "dictionary_phrase_entries_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "dictionary_lookups_user_id_idx" ON "dictionary_lookups"("user_id");
-- CreateIndex
CREATE INDEX "dictionary_lookups_created_at_idx" ON "dictionary_lookups"("created_at");
-- CreateIndex
CREATE INDEX "dictionary_lookups_text_query_lang_definition_lang_idx" ON "dictionary_lookups"("text", "query_lang", "definition_lang");
-- CreateIndex
CREATE INDEX "dictionary_words_standard_form_idx" ON "dictionary_words"("standard_form");
-- CreateIndex
CREATE INDEX "dictionary_words_query_lang_definition_lang_idx" ON "dictionary_words"("query_lang", "definition_lang");
-- CreateIndex
CREATE UNIQUE INDEX "dictionary_words_standard_form_query_lang_definition_lang_key" ON "dictionary_words"("standard_form", "query_lang", "definition_lang");
-- CreateIndex
CREATE INDEX "dictionary_phrases_standard_form_idx" ON "dictionary_phrases"("standard_form");
-- CreateIndex
CREATE INDEX "dictionary_phrases_query_lang_definition_lang_idx" ON "dictionary_phrases"("query_lang", "definition_lang");
-- CreateIndex
CREATE UNIQUE INDEX "dictionary_phrases_standard_form_query_lang_definition_lang_key" ON "dictionary_phrases"("standard_form", "query_lang", "definition_lang");
-- CreateIndex
CREATE INDEX "dictionary_word_entries_word_id_idx" ON "dictionary_word_entries"("word_id");
-- CreateIndex
CREATE INDEX "dictionary_word_entries_created_at_idx" ON "dictionary_word_entries"("created_at");
-- CreateIndex
CREATE INDEX "dictionary_phrase_entries_phrase_id_idx" ON "dictionary_phrase_entries"("phrase_id");
-- CreateIndex
CREATE INDEX "dictionary_phrase_entries_created_at_idx" ON "dictionary_phrase_entries"("created_at");
-- AddForeignKey
ALTER TABLE "dictionary_lookups" ADD CONSTRAINT "dictionary_lookups_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "dictionary_lookups" ADD CONSTRAINT "dictionary_lookups_dictionary_word_id_fkey" FOREIGN KEY ("dictionary_word_id") REFERENCES "dictionary_words"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "dictionary_lookups" ADD CONSTRAINT "dictionary_lookups_dictionary_phrase_id_fkey" FOREIGN KEY ("dictionary_phrase_id") REFERENCES "dictionary_phrases"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "dictionary_word_entries" ADD CONSTRAINT "dictionary_word_entries_word_id_fkey" FOREIGN KEY ("word_id") REFERENCES "dictionary_words"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "dictionary_phrase_entries" ADD CONSTRAINT "dictionary_phrase_entries_phrase_id_fkey" FOREIGN KEY ("phrase_id") REFERENCES "dictionary_phrases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,8 @@
-- DropIndex
DROP INDEX "dictionary_phrases_standard_form_query_lang_definition_lang_key";
-- DropIndex
DROP INDEX "dictionary_words_standard_form_query_lang_definition_lang_key";
-- RenameIndex
ALTER INDEX "pairs_folder_id_locale1_locale2_text1_key" RENAME TO "pairs_folder_id_language1_language2_text1_key";

View File

@@ -0,0 +1,30 @@
-- CreateTable
CREATE TABLE "translation_history" (
"id" SERIAL NOT NULL,
"user_id" TEXT,
"source_text" TEXT NOT NULL,
"source_language" VARCHAR(20) NOT NULL,
"target_language" VARCHAR(20) NOT NULL,
"translated_text" TEXT NOT NULL,
"source_ipa" TEXT,
"target_ipa" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "translation_history_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "translation_history_user_id_idx" ON "translation_history"("user_id");
-- CreateIndex
CREATE INDEX "translation_history_created_at_idx" ON "translation_history"("created_at");
-- CreateIndex
CREATE INDEX "translation_history_source_text_target_language_idx" ON "translation_history"("source_text", "target_language");
-- CreateIndex
CREATE INDEX "translation_history_translated_text_source_language_target__idx" ON "translation_history"("translated_text", "source_language", "target_language");
-- AddForeignKey
ALTER TABLE "translation_history" ADD CONSTRAINT "translation_history_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@@ -0,0 +1,11 @@
/*
Warnings:
- A unique constraint covering the columns `[folder_id,language1,language2,text1,text2]` on the table `pairs` will be added. If there are existing duplicate values, this will fail.
*/
-- DropIndex
DROP INDEX "pairs_folder_id_language1_language2_text1_key";
-- CreateIndex
CREATE UNIQUE INDEX "pairs_folder_id_language1_language2_text1_text2_key" ON "pairs"("folder_id", "language1", "language2", "text1", "text2");

View File

@@ -0,0 +1,7 @@
-- AlterTable
ALTER TABLE "pairs" ALTER COLUMN "language1" SET DATA TYPE TEXT,
ALTER COLUMN "language2" SET DATA TYPE TEXT;
-- AlterTable
ALTER TABLE "translation_history" ALTER COLUMN "source_language" SET DATA TYPE TEXT,
ALTER COLUMN "target_language" SET DATA TYPE TEXT;

View File

@@ -0,0 +1,94 @@
/*
Warnings:
- You are about to drop the column `dictionary_phrase_id` on the `dictionary_lookups` table. All the data in the column will be lost.
- You are about to drop the column `dictionary_word_id` on the `dictionary_lookups` table. All the data in the column will be lost.
- You are about to drop the `dictionary_phrase_entries` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `dictionary_phrases` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `dictionary_word_entries` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `dictionary_words` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "dictionary_lookups" DROP CONSTRAINT "dictionary_lookups_dictionary_phrase_id_fkey";
-- DropForeignKey
ALTER TABLE "dictionary_lookups" DROP CONSTRAINT "dictionary_lookups_dictionary_word_id_fkey";
-- DropForeignKey
ALTER TABLE "dictionary_phrase_entries" DROP CONSTRAINT "dictionary_phrase_entries_phrase_id_fkey";
-- DropForeignKey
ALTER TABLE "dictionary_word_entries" DROP CONSTRAINT "dictionary_word_entries_word_id_fkey";
-- DropIndex
DROP INDEX "dictionary_lookups_text_query_lang_definition_lang_idx";
-- AlterTable
ALTER TABLE "dictionary_lookups" DROP COLUMN "dictionary_phrase_id",
DROP COLUMN "dictionary_word_id",
ADD COLUMN "dictionary_item_id" INTEGER,
ADD COLUMN "normalized_text" TEXT NOT NULL DEFAULT '';
-- DropTable
DROP TABLE "dictionary_phrase_entries";
-- DropTable
DROP TABLE "dictionary_phrases";
-- DropTable
DROP TABLE "dictionary_word_entries";
-- DropTable
DROP TABLE "dictionary_words";
-- CreateTable
CREATE TABLE "dictionary_items" (
"id" SERIAL NOT NULL,
"frequency" INTEGER NOT NULL DEFAULT 1,
"standard_form" TEXT NOT NULL,
"query_lang" TEXT NOT NULL,
"definition_lang" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "dictionary_items_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "dictionary_entries" (
"id" SERIAL NOT NULL,
"item_id" INTEGER NOT NULL,
"ipa" TEXT,
"definition" TEXT NOT NULL,
"part_of_speech" TEXT,
"example" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "dictionary_entries_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "dictionary_items_standard_form_idx" ON "dictionary_items"("standard_form");
-- CreateIndex
CREATE INDEX "dictionary_items_query_lang_definition_lang_idx" ON "dictionary_items"("query_lang", "definition_lang");
-- CreateIndex
CREATE UNIQUE INDEX "dictionary_items_standard_form_query_lang_definition_lang_key" ON "dictionary_items"("standard_form", "query_lang", "definition_lang");
-- CreateIndex
CREATE INDEX "dictionary_entries_item_id_idx" ON "dictionary_entries"("item_id");
-- CreateIndex
CREATE INDEX "dictionary_entries_created_at_idx" ON "dictionary_entries"("created_at");
-- CreateIndex
CREATE INDEX "dictionary_lookups_normalized_text_idx" ON "dictionary_lookups"("normalized_text");
-- AddForeignKey
ALTER TABLE "dictionary_lookups" ADD CONSTRAINT "dictionary_lookups_dictionary_item_id_fkey" FOREIGN KEY ("dictionary_item_id") REFERENCES "dictionary_items"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "dictionary_entries" ADD CONSTRAINT "dictionary_entries_item_id_fkey" FOREIGN KEY ("item_id") REFERENCES "dictionary_items"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,12 @@
/*
Warnings:
- A unique constraint covering the columns `[username]` on the table `user` will be added. If there are existing duplicate values, this will fail.
*/
-- AlterTable
ALTER TABLE "user" ADD COLUMN "displayUsername" TEXT,
ADD COLUMN "username" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "user_username_key" ON "user"("username");

View File

@@ -1,4 +1,3 @@
generator client { generator client {
provider = "prisma-client" provider = "prisma-client"
output = "../generated/prisma" output = "../generated/prisma"
@@ -8,59 +7,29 @@ datasource db {
provider = "postgresql" provider = "postgresql"
} }
model Pair {
id Int @id @default(autoincrement())
locale1 String @db.VarChar(10)
locale2 String @db.VarChar(10)
text1 String
text2 String
ipa1 String?
ipa2 String?
folderId Int @map("folder_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
folder Folder @relation(fields: [folderId], references: [id], onDelete: Cascade)
@@unique([folderId, locale1, locale2, text1])
@@index([folderId])
@@map("pairs")
}
model Folder {
id Int @id @default(autoincrement())
name String
userId String @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
pairs Pair[]
@@index([userId])
@@map("folders")
}
model User { model User {
id String @id id String @id
name String name String
email String email String @unique
emailVerified Boolean @default(false) emailVerified Boolean @default(false)
image String? image String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
sessions Session[] displayUsername String?
username String? @unique
accounts Account[] accounts Account[]
dictionaryLookUps DictionaryLookUp[]
folders Folder[] folders Folder[]
sessions Session[]
translationHistories TranslationHistory[]
@@unique([email])
@@map("user") @@map("user")
} }
model Session { model Session {
id String @id id String @id
expiresAt DateTime expiresAt DateTime
token String token String @unique
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
ipAddress String? ipAddress String?
@@ -68,7 +37,6 @@ model Session {
userId String userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade) user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([token])
@@index([userId]) @@index([userId])
@@map("session") @@map("session")
} }
@@ -78,7 +46,6 @@ model Account {
accountId String accountId String
providerId String providerId String
userId String userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String? accessToken String?
refreshToken String? refreshToken String?
idToken String? idToken String?
@@ -88,6 +55,7 @@ model Account {
password String? password String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId]) @@index([userId])
@@map("account") @@map("account")
@@ -104,3 +72,105 @@ model Verification {
@@index([identifier]) @@index([identifier])
@@map("verification") @@map("verification")
} }
model Pair {
id Int @id @default(autoincrement())
language1 String
language2 String
text1 String
text2 String
ipa1 String?
ipa2 String?
folderId Int @map("folder_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
folder Folder @relation(fields: [folderId], references: [id], onDelete: Cascade)
@@unique([folderId, language1, language2, text1, text2])
@@index([folderId])
@@map("pairs")
}
model Folder {
id Int @id @default(autoincrement())
name String
userId String @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
pairs Pair[]
@@index([userId])
@@map("folders")
}
model DictionaryLookUp {
id Int @id @default(autoincrement())
userId String? @map("user_id")
text String
queryLang String @map("query_lang")
definitionLang String @map("definition_lang")
createdAt DateTime @default(now()) @map("created_at")
dictionaryItemId Int? @map("dictionary_item_id")
normalizedText String @default("") @map("normalized_text")
dictionaryItem DictionaryItem? @relation(fields: [dictionaryItemId], references: [id])
user User? @relation(fields: [userId], references: [id])
@@index([userId])
@@index([createdAt])
@@index([normalizedText])
@@map("dictionary_lookups")
}
model DictionaryItem {
id Int @id @default(autoincrement())
frequency Int @default(1)
standardForm String @map("standard_form")
queryLang String @map("query_lang")
definitionLang String @map("definition_lang")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
entries DictionaryEntry[]
lookups DictionaryLookUp[]
@@unique([standardForm, queryLang, definitionLang])
@@index([standardForm])
@@index([queryLang, definitionLang])
@@map("dictionary_items")
}
model DictionaryEntry {
id Int @id @default(autoincrement())
itemId Int @map("item_id")
ipa String?
definition String
partOfSpeech String? @map("part_of_speech")
example String
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
item DictionaryItem @relation(fields: [itemId], references: [id], onDelete: Cascade)
@@index([itemId])
@@index([createdAt])
@@map("dictionary_entries")
}
model TranslationHistory {
id Int @id @default(autoincrement())
userId String? @map("user_id")
sourceText String @map("source_text")
sourceLanguage String @map("source_language")
targetLanguage String @map("target_language")
translatedText String @map("translated_text")
sourceIpa String? @map("source_ipa")
targetIpa String? @map("target_ipa")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User? @relation(fields: [userId], references: [id])
@@index([userId])
@@index([createdAt])
@@index([sourceText, targetLanguage])
@@index([translatedText, sourceLanguage, targetLanguage])
@@map("translation_history")
}

View File

@@ -3,9 +3,11 @@
import { useState, useEffect, useCallback } from "react"; import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Letter, SupportedAlphabets } from "@/lib/interfaces"; import { Letter, SupportedAlphabets } from "@/lib/interfaces";
import IconClick from "@/components/ui/buttons/IconClick"; import { IconClick, CircleToggleButton, CircleButton, PrimaryButton } from "@/design-system/base/button";
import IMAGES from "@/config/images"; import { IMAGES } from "@/config/images";
import { ChevronLeft, ChevronRight } from "lucide-react"; import { ChevronLeft, ChevronRight } from "lucide-react";
import { PageLayout } from "@/components/ui/PageLayout";
import { Card } from "@/design-system/base/card";
interface AlphabetCardProps { interface AlphabetCardProps {
alphabet: Letter[]; alphabet: Letter[];
@@ -13,7 +15,7 @@ interface AlphabetCardProps {
onBack: () => void; onBack: () => void;
} }
export default function AlphabetCard({ alphabet, alphabetType, onBack }: AlphabetCardProps) { export function AlphabetCard({ alphabet, alphabetType, onBack }: AlphabetCardProps) {
const t = useTranslations("alphabet"); const t = useTranslations("alphabet");
const [currentIndex, setCurrentIndex] = useState(0); const [currentIndex, setCurrentIndex] = useState(0);
const [showIPA, setShowIPA] = useState(true); const [showIPA, setShowIPA] = useState(true);
@@ -97,12 +99,11 @@ export default function AlphabetCard({ alphabet, alphabetType, onBack }: Alphabe
}; };
return ( return (
<div className="min-h-[calc(100vh-64px)] bg-[#35786f] flex items-center justify-center px-4 py-8"> <PageLayout className="relative">
<div className="w-full max-w-2xl"> {/* 右上角返回按钮 - outside the white card */}
{/* 返回按钮 */}
<div className="flex justify-end mb-4"> <div className="flex justify-end mb-4">
<IconClick <IconClick
size={32} size="lg"
alt="close" alt="close"
src={IMAGES.close} src={IMAGES.close}
onClick={onBack} onClick={onBack}
@@ -110,61 +111,51 @@ export default function AlphabetCard({ alphabet, alphabetType, onBack }: Alphabe
/> />
</div> </div>
{/* 主卡片 */} {/* 白色主卡片容器 */}
<div className="bg-white rounded-2xl shadow-xl p-8 md:p-12"> <Card padding="xl">
{/* 进度指示器 */} {/* 顶部进度指示器和显示选项按钮 */}
<div className="flex justify-between items-center mb-6"> <div className="flex justify-between items-center mb-6">
{/* 当前字母进度 */}
<span className="text-sm text-gray-500"> <span className="text-sm text-gray-500">
{currentIndex + 1} / {alphabet.length} {currentIndex + 1} / {alphabet.length}
</span> </span>
{/* 显示选项切换按钮组 */}
<div className="flex gap-2 flex-wrap"> <div className="flex gap-2 flex-wrap">
<button <CircleToggleButton
selected={showLetter}
onClick={() => setShowLetter(!showLetter)} onClick={() => setShowLetter(!showLetter)}
className={`px-3 py-1 rounded-full text-sm transition-colors ${
showLetter
? "bg-[#35786f] text-white"
: "bg-gray-200 text-gray-600"
}`}
> >
{t("letter")} {t("letter")}
</button> </CircleToggleButton>
<button {/* IPA 音标显示切换 */}
<CircleToggleButton
selected={showIPA}
onClick={() => setShowIPA(!showIPA)} onClick={() => setShowIPA(!showIPA)}
className={`px-3 py-1 rounded-full text-sm transition-colors ${
showIPA
? "bg-[#35786f] text-white"
: "bg-gray-200 text-gray-600"
}`}
> >
IPA IPA
</button> </CircleToggleButton>
{/* 罗马音显示切换(仅日语显示) */}
{hasRomanization && ( {hasRomanization && (
<button <CircleToggleButton
selected={showRoman}
onClick={() => setShowRoman(!showRoman)} onClick={() => setShowRoman(!showRoman)}
className={`px-3 py-1 rounded-full text-sm transition-colors ${
showRoman
? "bg-[#35786f] text-white"
: "bg-gray-200 text-gray-600"
}`}
> >
{t("roman")} {t("roman")}
</button> </CircleToggleButton>
)} )}
<button {/* 随机模式切换 */}
<CircleToggleButton
selected={isRandomMode}
onClick={() => setIsRandomMode(!isRandomMode)} onClick={() => setIsRandomMode(!isRandomMode)}
className={`px-3 py-1 rounded-full text-sm transition-colors ${
isRandomMode
? "bg-[#35786f] text-white"
: "bg-gray-200 text-gray-600"
}`}
> >
{t("random")} {t("random")}
</button> </CircleToggleButton>
</div> </div>
</div> </div>
{/* 字母显示区域 */} {/* 字母主要内容显示区域 */}
<div className="text-center mb-8"> <div className="text-center mb-8">
{/* 字母本身(可隐藏) */}
{showLetter ? ( {showLetter ? (
<div className="text-6xl md:text-8xl font-bold text-gray-800 mb-4"> <div className="text-6xl md:text-8xl font-bold text-gray-800 mb-4">
{currentLetter.letter} {currentLetter.letter}
@@ -175,12 +166,14 @@ export default function AlphabetCard({ alphabet, alphabetType, onBack }: Alphabe
</div> </div>
)} )}
{/* IPA 音标显示 */}
{showIPA && ( {showIPA && (
<div className="text-2xl md:text-3xl text-gray-600 mb-2"> <div className="text-2xl md:text-3xl text-gray-600 mb-2">
{currentLetter.letter_sound_ipa} {currentLetter.letter_sound_ipa}
</div> </div>
)} )}
{/* 罗马音显示(日语) */}
{showRoman && hasRomanization && currentLetter.roman_letter && ( {showRoman && hasRomanization && currentLetter.roman_letter && (
<div className="text-lg md:text-xl text-gray-500"> <div className="text-lg md:text-xl text-gray-500">
{currentLetter.roman_letter} {currentLetter.roman_letter}
@@ -188,54 +181,33 @@ export default function AlphabetCard({ alphabet, alphabetType, onBack }: Alphabe
)} )}
</div> </div>
{/* 导航控制 */} {/* 底部导航控制区域 */}
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<button {/* 上一个按钮 */}
onClick={goToPrevious} <CircleButton onClick={goToPrevious} aria-label="上一个字母">
className="p-3 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors" <ChevronLeft size={20} />
aria-label="上一个字母" </CircleButton>
>
<ChevronLeft size={24} />
</button>
{/* 中间区域:随机按钮 */}
<div className="flex gap-2 items-center"> <div className="flex gap-2 items-center">
{isRandomMode ? ( {isRandomMode && (
<button <PrimaryButton
onClick={goToRandom} onClick={goToRandom}
className="px-4 py-2 rounded-full bg-[#35786f] text-white text-sm font-medium hover:bg-[#2d5f58] transition-colors" className="rounded-full px-4 py-2 text-sm"
> >
{t("randomNext")} {t("randomNext")}
</button> </PrimaryButton>
) : (
<div className="flex gap-1 flex-wrap max-w-xs justify-center">
{alphabet.slice(0, 20).map((_, index) => (
<div
key={index}
className={`h-2 rounded-full transition-all ${
index === currentIndex
? "w-8 bg-[#35786f]"
: "w-2 bg-gray-300"
}`}
/>
))}
{alphabet.length > 20 && (
<div className="text-xs text-gray-500 flex items-center">...</div>
)}
</div>
)} )}
</div> </div>
<button {/* 下一个按钮 */}
onClick={goToNext} <CircleButton onClick={goToNext} aria-label="下一个字母">
className="p-3 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors" <ChevronRight size={20} />
aria-label="下一个字母" </CircleButton>
>
<ChevronRight size={24} />
</button>
</div>
</div> </div>
</Card>
{/* 操作提示 */} {/* 底部操作提示文字 */}
<div className="text-center mt-6 text-white text-sm"> <div className="text-center mt-6 text-white text-sm">
<p> <p>
{isRandomMode {isRandomMode
@@ -244,15 +216,14 @@ export default function AlphabetCard({ alphabet, alphabetType, onBack }: Alphabe
} }
</p> </p>
</div> </div>
</div>
{/* 触摸事件处理 */} {/* 全屏触摸事件监听层(用于滑动切换) */}
<div <div
className="absolute inset-0 pointer-events-none" className="absolute inset-0 pointer-events-none"
onTouchStart={onTouchStart} onTouchStart={onTouchStart}
onTouchMove={onTouchMove} onTouchMove={onTouchMove}
onTouchEnd={onTouchEnd} onTouchEnd={onTouchEnd}
/> />
</div> </PageLayout>
); );
} }

View File

@@ -1,6 +1,6 @@
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import IconClick from "@/components/ui/buttons/IconClick"; import { IconClick } from "@/design-system/base/button";
import IMAGES from "@/config/images"; import { IMAGES } from "@/config/images";
import { Letter, SupportedAlphabets } from "@/lib/interfaces"; import { Letter, SupportedAlphabets } from "@/lib/interfaces";
import { import {
Dispatch, Dispatch,
@@ -12,7 +12,7 @@ import {
} from "react"; } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
export default function MemoryCard({ export function MemoryCard({
alphabet, alphabet,
setChosenAlphabet, setChosenAlphabet,
}: { }: {
@@ -45,10 +45,10 @@ export default function MemoryCard({
className="w-full flex justify-center items-center" className="w-full flex justify-center items-center"
onKeyDown={(e: KeyboardEvent<HTMLDivElement>) => e.preventDefault()} onKeyDown={(e: KeyboardEvent<HTMLDivElement>) => e.preventDefault()}
> >
<div className="m-4 p-4 w-full md:w-[60dvw] flex-col rounded-2xl shadow border-gray-200 border flex justify-center items-center"> <div className="m-4 p-4 w-full md:w-[60dvw] flex-col rounded-lg shadow border-gray-200 border flex justify-center items-center">
<div className="w-full flex justify-end items-center"> <div className="w-full flex justify-end items-center">
<IconClick <IconClick
size={32} size="lg"
alt="close" alt="close"
src={IMAGES.close} src={IMAGES.close}
onClick={() => setChosenAlphabet(null)} onClick={() => setChosenAlphabet(null)}
@@ -64,13 +64,13 @@ export default function MemoryCard({
</div> </div>
<div className="flex flex-row mt-32 items-center justify-center gap-2"> <div className="flex flex-row mt-32 items-center justify-center gap-2">
<IconClick <IconClick
size={48} size="lg"
alt="refresh" alt="refresh"
src={IMAGES.refresh} src={IMAGES.refresh}
onClick={refresh} onClick={refresh}
></IconClick> ></IconClick>
<IconClick <IconClick
size={48} size="lg"
alt="more" alt="more"
src={IMAGES.more_horiz} src={IMAGES.more_horiz}
onClick={() => setMore(!more)} onClick={() => setMore(!more)}

View File

@@ -3,9 +3,9 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { Letter, SupportedAlphabets } from "@/lib/interfaces"; import { Letter, SupportedAlphabets } from "@/lib/interfaces";
import Container from "@/components/ui/Container"; import { PageLayout } from "@/components/ui/PageLayout";
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import AlphabetCard from "./AlphabetCard"; import { AlphabetCard } from "./AlphabetCard";
export default function Alphabet() { export default function Alphabet() {
const t = useTranslations("alphabet"); const t = useTranslations("alphabet");
@@ -48,16 +48,19 @@ export default function Alphabet() {
// 语言选择界面 // 语言选择界面
if (!chosenAlphabet) { if (!chosenAlphabet) {
return ( return (
<div className="min-h-[calc(100vh-64px)] bg-[#35786f] flex flex-col items-center justify-center px-4"> <PageLayout>
<Container className="p-8 max-w-2xl w-full text-center"> {/* 页面标题 */}
<h1 className="text-4xl md:text-5xl font-bold text-gray-800 mb-4"> <h1 className="text-4xl md:text-5xl font-bold text-gray-800 mb-4">
{t("chooseCharacters")} {t("chooseCharacters")}
</h1> </h1>
{/* 副标题说明 */}
<p className="text-gray-600 mb-8 text-lg"> <p className="text-gray-600 mb-8 text-lg">
</p> </p>
{/* 语言选择按钮网格 */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* 日语假名选项 */}
<LightButton <LightButton
onClick={() => setChosenAlphabet("japanese")} onClick={() => setChosenAlphabet("japanese")}
className="p-6 text-lg font-medium hover:scale-105 transition-transform" className="p-6 text-lg font-medium hover:scale-105 transition-transform"
@@ -68,6 +71,7 @@ export default function Alphabet() {
</div> </div>
</LightButton> </LightButton>
{/* 英语字母选项 */}
<LightButton <LightButton
onClick={() => setChosenAlphabet("english")} onClick={() => setChosenAlphabet("english")}
className="p-6 text-lg font-medium hover:scale-105 transition-transform" className="p-6 text-lg font-medium hover:scale-105 transition-transform"
@@ -78,6 +82,7 @@ export default function Alphabet() {
</div> </div>
</LightButton> </LightButton>
{/* 维吾尔语字母选项 */}
<LightButton <LightButton
onClick={() => setChosenAlphabet("uyghur")} onClick={() => setChosenAlphabet("uyghur")}
className="p-6 text-lg font-medium hover:scale-105 transition-transform" className="p-6 text-lg font-medium hover:scale-105 transition-transform"
@@ -88,6 +93,7 @@ export default function Alphabet() {
</div> </div>
</LightButton> </LightButton>
{/* 世界语字母选项 */}
<LightButton <LightButton
onClick={() => setChosenAlphabet("esperanto")} onClick={() => setChosenAlphabet("esperanto")}
className="p-6 text-lg font-medium hover:scale-105 transition-transform" className="p-6 text-lg font-medium hover:scale-105 transition-transform"
@@ -98,30 +104,25 @@ export default function Alphabet() {
</div> </div>
</LightButton> </LightButton>
</div> </div>
</Container> </PageLayout>
</div>
); );
} }
// 加载状态 // 加载状态
if (loadingState === "loading") { if (loadingState === "loading") {
return ( return (
<div className="min-h-[calc(100vh-64px)] bg-[#35786f] flex items-center justify-center"> <PageLayout>
<Container className="p-8 text-center"> <div className="text-2xl text-gray-600 text-center">{t("loading")}</div>
<div className="text-2xl text-gray-600">{t("loading")}</div> </PageLayout>
</Container>
</div>
); );
} }
// 错误状态 // 错误状态
if (loadingState === "error") { if (loadingState === "error") {
return ( return (
<div className="min-h-[calc(100vh-64px)] bg-[#35786f] flex items-center justify-center"> <PageLayout>
<Container className="p-8 text-center"> <div className="text-2xl text-red-600 text-center">{t("loadFailed")}</div>
<div className="text-2xl text-red-600">{t("loadFailed")}</div> </PageLayout>
</Container>
</div>
); );
} }

View File

@@ -0,0 +1,45 @@
import { TSharedEntry } from "@/shared/dictionary-type";
interface DictionaryEntryProps {
entry: TSharedEntry;
}
export function DictionaryEntry({ entry }: DictionaryEntryProps) {
return (
<div>
{/* 音标和词性 */}
<div className="flex items-center gap-3 mb-3">
{entry.ipa && (
<span className="text-gray-600 text-lg">
[{entry.ipa}]
</span>
)}
{entry.partOfSpeech && (
<span className="px-3 py-1 bg-[#35786f] text-white text-sm rounded-full">
{entry.partOfSpeech}
</span>
)}
</div>
{/* 释义 */}
<div className="mb-3">
<h3 className="text-sm font-semibold text-gray-700 mb-1">
</h3>
<p className="text-gray-800">{entry.definition}</p>
</div>
{/* 例句 */}
{entry.example && (
<div>
<h3 className="text-sm font-semibold text-gray-700 mb-1">
</h3>
<p className="text-gray-700 pl-4 border-l-4 border-[#35786f]">
{entry.example}
</p>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,117 @@
"use client";
import { LightButton } from "@/design-system/base/button";
import { Input } from "@/design-system/base/input";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { POPULAR_LANGUAGES } from "./constants";
interface SearchFormProps {
defaultQueryLang?: string;
defaultDefinitionLang?: string;
}
export function SearchForm({ defaultQueryLang = "english", defaultDefinitionLang = "chinese" }: SearchFormProps) {
const t = useTranslations("dictionary");
const [queryLang, setQueryLang] = useState(defaultQueryLang);
const [definitionLang, setDefinitionLang] = useState(defaultDefinitionLang);
const router = useRouter();
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const searchQuery = formData.get("searchQuery") as string;
if (!searchQuery?.trim()) return;
const params = new URLSearchParams({
q: searchQuery,
ql: queryLang,
dl: definitionLang,
});
router.push(`/dictionary?${params.toString()}`);
};
return (
<>
{/* 页面标题 */}
<div className="text-center mb-8">
<h1 className="text-4xl md:text-5xl font-bold text-gray-800 mb-4">
{t("title")}
</h1>
<p className="text-gray-700 text-lg">
{t("description")}
</p>
</div>
{/* 搜索表单 */}
<form onSubmit={handleSubmit} className="flex flex-col sm:flex-row gap-2">
<Input
type="text"
name="searchQuery"
defaultValue=""
placeholder={t("searchPlaceholder")}
variant="search"
required
/>
<LightButton
type="submit"
className="px-6 py-3 whitespace-nowrap text-center sm:min-w-30"
>
{t("search")}
</LightButton>
</form>
{/* 语言设置 */}
<div className="mt-4 bg-white/20 rounded-lg p-4">
<div className="mb-3">
<span className="text-gray-800 font-semibold">{t("languageSettings")}</span>
</div>
<div className="space-y-4">
{/* 查询语言 */}
<div>
<label className="block text-gray-700 text-sm mb-2">
{t("queryLanguage")} ({t("queryLanguageHint")})
</label>
<div className="flex flex-wrap gap-2">
{POPULAR_LANGUAGES.map((lang) => (
<LightButton
key={lang.code}
type="button"
selected={queryLang === lang.code}
onClick={() => setQueryLang(lang.code)}
className="text-sm px-3 py-1"
>
{lang.nativeName}
</LightButton>
))}
</div>
</div>
{/* 释义语言 */}
<div>
<label className="block text-gray-700 text-sm mb-2">
{t("definitionLanguage")} ({t("definitionLanguageHint")})
</label>
<div className="flex flex-wrap gap-2">
{POPULAR_LANGUAGES.map((lang) => (
<LightButton
key={lang.code}
type="button"
selected={definitionLang === lang.code}
onClick={() => setDefinitionLang(lang.code)}
className="text-sm px-3 py-1"
>
{lang.nativeName}
</LightButton>
))}
</div>
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,122 @@
"use client";
import { Plus, RefreshCw } from "lucide-react";
import { CircleButton, LightButton } from "@/design-system/base/button";
import { toast } from "sonner";
import { actionCreatePair } from "@/modules/folder/folder-aciton";
import { TSharedItem } from "@/shared/dictionary-type";
import { TSharedFolder } from "@/shared/folder-type";
import { actionLookUpDictionary } from "@/modules/dictionary/dictionary-action";
import { useRouter } from "next/navigation";
type Session = {
user: {
id: string;
name?: string | null;
email?: string | null;
image?: string | null;
};
} | null;
interface SaveButtonClientProps {
session: Session;
folders: TSharedFolder[];
searchResult: TSharedItem;
queryLang: string;
definitionLang: string;
}
export function SaveButtonClient({ session, folders, searchResult, queryLang, definitionLang }: SaveButtonClientProps) {
const handleSave = async () => {
if (!session) {
toast.error("Please login first");
return;
}
if (folders.length === 0) {
toast.error("Please create a folder first");
return;
}
const folderSelect = document.getElementById("folder-select") as HTMLSelectElement;
const folderId = folderSelect?.value ? Number(folderSelect.value) : folders[0]?.id;
const definition = searchResult.entries.reduce((p, e) => {
return { ...p, definition: p.definition + ' | ' + e.definition };
}).definition;
try {
await actionCreatePair({
text1: searchResult.standardForm,
text2: definition,
language1: queryLang,
language2: definitionLang,
ipa1: searchResult.entries[0].ipa,
folderId: folderId,
});
const folderName = folders.find((f) => f.id === folderId)?.name || "Unknown";
toast.success(`Saved to ${folderName}`);
} catch (error) {
toast.error("Save failed");
}
};
return (
<CircleButton
onClick={handleSave}
className="w-10 h-10 shrink-0"
title="Save to folder"
>
<Plus />
</CircleButton>
);
}
interface ReLookupButtonClientProps {
searchQuery: string;
queryLang: string;
definitionLang: string;
}
export function ReLookupButtonClient({ searchQuery, queryLang, definitionLang }: ReLookupButtonClientProps) {
const router = useRouter();
const handleRelookup = async () => {
const getNativeName = (code: string): string => {
const popularLanguages: Record<string, string> = {
english: "English",
chinese: "中文",
japanese: "日本語",
korean: "한국어",
italian: "Italiano",
uyghur: "ئۇيغۇرچە",
};
return popularLanguages[code] || code;
};
try {
await actionLookUpDictionary({
text: searchQuery,
queryLang: getNativeName(queryLang),
definitionLang: getNativeName(definitionLang),
forceRelook: true
});
toast.success("Re-lookup successful");
// 刷新页面以显示新结果
router.refresh();
} catch (error) {
toast.error("Re-lookup failed");
}
};
return (
<LightButton
onClick={handleRelookup}
className="flex items-center gap-2 px-4 py-2 text-sm"
leftIcon={<RefreshCw className="w-4 h-4" />}
>
Re-lookup
</LightButton>
);
}

View File

@@ -0,0 +1,93 @@
import { auth } from "@/auth";
import { DictionaryEntry } from "./DictionaryEntry";
import { TSharedItem } from "@/shared/dictionary-type";
import { SaveButtonClient, ReLookupButtonClient } from "./SearchResult.client";
import { headers } from "next/headers";
import { actionGetFoldersByUserId } from "@/modules/folder/folder-aciton";
import { TSharedFolder } from "@/shared/folder-type";
interface SearchResultProps {
searchResult: TSharedItem | null;
searchQuery: string;
queryLang: string;
definitionLang: string;
}
export async function SearchResult({
searchResult,
searchQuery,
queryLang,
definitionLang
}: SearchResultProps) {
// 获取用户会话和文件夹
const session = await auth.api.getSession({ headers: await headers() });
let folders: TSharedFolder[] = [];
if (session?.user?.id) {
const result = await actionGetFoldersByUserId(session.user.id as string);
if (result.success && result.data) {
folders = result.data;
}
}
return (
<div className="space-y-6">
{!searchResult ? (
<div className="text-center py-12 bg-white/20 rounded-lg">
<p className="text-gray-800 text-xl">No results found</p>
<p className="text-gray-600 mt-2">Try other words</p>
</div>
) : (
<div className="bg-white rounded-lg p-6 shadow-lg">
{/* 标题和保存按钮 */}
<div className="flex items-start justify-between mb-6">
<div className="flex-1">
<h2 className="text-3xl font-bold text-gray-800 mb-2">
{searchResult.standardForm}
</h2>
</div>
<div className="flex items-center gap-2 ml-4">
{session && folders.length > 0 && (
<select
id="folder-select"
className="px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[#35786f]"
>
{folders.map((folder) => (
<option key={folder.id} value={folder.id}>
{folder.name}
</option>
))}
</select>
)}
<SaveButtonClient
session={session}
folders={folders}
searchResult={searchResult}
queryLang={queryLang}
definitionLang={definitionLang}
/>
</div>
</div>
{/* 条目列表 */}
<div className="space-y-6">
{searchResult.entries.map((entry, index) => (
<div key={index} className="border-t border-gray-200 pt-4">
<DictionaryEntry entry={entry} />
</div>
))}
</div>
{/* 重新查询按钮 */}
<div className="border-t border-gray-200 pt-4 mt-4">
<ReLookupButtonClient
searchQuery={searchQuery}
queryLang={queryLang}
definitionLang={definitionLang}
/>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,8 @@
export const POPULAR_LANGUAGES = [
{ code: "english", name: "英语", nativeName: "English" },
{ code: "chinese", name: "中文", nativeName: "中文" },
{ code: "japanese", name: "日语", nativeName: "日本語" },
{ code: "korean", name: "韩语", nativeName: "한국어" },
{ code: "italian", name: "意大利语", nativeName: "Italiano" },
{ code: "uyghur", name: "维吾尔语", nativeName: "ئۇيغۇرچە" },
] as const;

View File

@@ -0,0 +1,75 @@
import { PageLayout } from "@/components/ui/PageLayout";
import { SearchForm } from "./SearchForm";
import { SearchResult } from "./SearchResult";
import { getTranslations } from "next-intl/server";
import { actionLookUpDictionary } from "@/modules/dictionary/dictionary-action";
import { TSharedItem } from "@/shared/dictionary-type";
interface DictionaryPageProps {
searchParams: Promise<{ q?: string; ql?: string; dl?: string; }>;
}
export default async function DictionaryPage({ searchParams }: DictionaryPageProps) {
const t = await getTranslations("dictionary");
// 从 searchParams 获取搜索参数
const { q: searchQuery, ql: queryLang = "english", dl: definitionLang = "chinese" } = await searchParams;
// 如果有搜索查询,获取搜索结果
let searchResult: TSharedItem | undefined | null = null;
if (searchQuery) {
const getNativeName = (code: string): string => {
const popularLanguages: Record<string, string> = {
english: "English",
chinese: "中文",
japanese: "日本語",
korean: "한국어",
italian: "Italiano",
uyghur: "ئۇيغۇرچە",
};
return popularLanguages[code] || code;
};
const result = await actionLookUpDictionary({
text: searchQuery,
queryLang: getNativeName(queryLang),
definitionLang: getNativeName(definitionLang),
forceRelook: false
});
if (result.success && result.data) {
searchResult = result.data;
}
}
return (
<PageLayout>
{/* 搜索区域 */}
<div className="mb-8">
<SearchForm
defaultQueryLang={queryLang}
defaultDefinitionLang={definitionLang}
/>
</div>
{/* 搜索结果区域 */}
<div>
{searchQuery && (
<SearchResult
searchResult={searchResult}
searchQuery={searchQuery}
queryLang={queryLang}
definitionLang={definitionLang}
/>
)}
{!searchQuery && (
<div className="text-center py-12">
<div className="text-6xl mb-4">📚</div>
<p className="text-gray-800 text-xl mb-2">{t("welcomeTitle")}</p>
<p className="text-gray-600">{t("welcomeHint")}</p>
</div>
)}
</div>
</PageLayout>
);
}

View File

@@ -1,36 +1,43 @@
"use client"; "use client";
import Container from "@/components/ui/Container";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Center } from "@/components/common/Center";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import Link from "next/link"; import Link from "next/link";
import { Folder } from "../../../../generated/prisma/browser";
import { Folder as Fd } from "lucide-react"; import { Folder as Fd } from "lucide-react";
import { TSharedFolderWithTotalPairs } from "@/shared/folder-type";
import { PageLayout } from "@/components/ui/PageLayout";
import { PrimaryButton } from "@/design-system/base/button";
interface FolderSelectorProps { interface FolderSelectorProps {
folders: (Folder & { total: number })[]; folders: TSharedFolderWithTotalPairs[];
} }
const FolderSelector: React.FC<FolderSelectorProps> = ({ folders }) => { const FolderSelector: React.FC<FolderSelectorProps> = ({ folders }) => {
const t = useTranslations("memorize.folder_selector"); const t = useTranslations("memorize.folder_selector");
const router = useRouter(); const router = useRouter();
return ( return (
<Center> <PageLayout>
<Container className="p-6 gap-4 flex flex-col"> {folders.length === 0 ? (
{(folders.length === 0 && ( // 空状态 - 显示提示和跳转按钮
<h1 className="text-2xl text-gray-900 font-light"> <div className="text-center">
<h1 className="text-2xl md:text-3xl font-bold text-gray-800 mb-4">
{t("noFolders")} {t("noFolders")}
<Link className="text-blue-900 border-b" href={"/folders"}>
folders
</Link>
</h1> </h1>
)) || ( <Link href="/folders">
<PrimaryButton className="px-6 py-2">
Go to Folders
</PrimaryButton>
</Link>
</div>
) : (
<> <>
<h1 className="text-2xl text-gray-900 font-light"> {/* 页面标题 */}
<h1 className="text-2xl md:text-3xl font-bold text-gray-800 mb-6">
{t("selectFolder")} {t("selectFolder")}
</h1> </h1>
<div className="text-gray-900 border border-gray-200 rounded-2xl max-h-96 overflow-y-auto"> {/* 文件夹列表 */}
<div className="border border-gray-200 rounded-lg max-h-96 overflow-y-auto">
{folders {folders
.toSorted((a, b) => a.id - b.id) .toSorted((a, b) => a.id - b.id)
.map((folder) => ( .map((folder) => (
@@ -39,26 +46,48 @@ const FolderSelector: React.FC<FolderSelectorProps> = ({ folders }) => {
onClick={() => onClick={() =>
router.push(`/memorize?folder_id=${folder.id}`) router.push(`/memorize?folder_id=${folder.id}`)
} }
className="flex flex-row justify-center items-center group p-2 gap-2 hover:cursor-pointer hover:bg-gray-50" className="flex flex-row items-center p-4 gap-3 hover:cursor-pointer hover:bg-gray-50 transition-colors border-b border-gray-100 last:border-b-0"
> >
<Fd /> {/* 文件夹图标 */}
<div className="flex-1 flex gap-2"> <div className="shrink-0">
<span className="group-hover:text-blue-500"> <Fd className="text-gray-600" size="md" />
</div>
{/* 文件夹信息 */}
<div className="flex-1">
<div className="font-medium text-gray-900">
{folder.name}
</div>
<div className="text-sm text-gray-500">
{t("folderInfo", { {t("folderInfo", {
id: folder.id, id: folder.id,
name: folder.name, name: folder.name,
count: folder.total, count: folder.total,
})} })}
</span> </div>
</div>
{/* 右箭头 */}
<div className="text-gray-400">
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5l7 7-7 7"
/>
</svg>
</div> </div>
</div> </div>
))} ))}
</div> </div>
</> </>
)} )}
</Container> </PageLayout>
</Center>
); );
}; };
export default FolderSelector; export { FolderSelector };

View File

@@ -1,21 +1,21 @@
"use client"; "use client";
import { useState } from "react"; import { useState } from "react";
import LightButton from "@/components/ui/buttons/LightButton"; import { LinkButton, CircleToggleButton, LightButton } from "@/design-system/base/button";
import { useAudioPlayer } from "@/hooks/useAudioPlayer"; import { useAudioPlayer } from "@/hooks/useAudioPlayer";
import { getTTSAudioUrl } from "@/lib/browser/tts"; import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/bigmodel/tts";
import { VOICES } from "@/config/locales";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import localFont from "next/font/local"; import localFont from "next/font/local";
import { isNonNegativeInteger, SeededRandom } from "@/lib/utils"; import { isNonNegativeInteger, SeededRandom } from "@/utils/random";
import { Pair } from "../../../../generated/prisma/browser"; import { TSharedPair } from "@/shared/folder-type";
import { PageLayout } from "@/components/ui/PageLayout";
const myFont = localFont({ const myFont = localFont({
src: "../../../../public/fonts/NotoNaskhArabic-VariableFont_wght.ttf", src: "../../../../public/fonts/NotoNaskhArabic-VariableFont_wght.ttf",
}); });
interface MemorizeProps { interface MemorizeProps {
textPairs: Pair[]; textPairs: TSharedPair[];
} }
const Memorize: React.FC<MemorizeProps> = ({ textPairs }) => { const Memorize: React.FC<MemorizeProps> = ({ textPairs }) => {
@@ -28,7 +28,11 @@ const Memorize: React.FC<MemorizeProps> = ({ textPairs }) => {
const { load, play } = useAudioPlayer(); const { load, play } = useAudioPlayer();
if (textPairs.length === 0) { if (textPairs.length === 0) {
return <p>{t("noTextPairs")}</p>; return (
<PageLayout>
<p className="text-gray-700 text-center">{t("noTextPairs")}</p>
</PageLayout>
);
} }
const rng = new SeededRandom(textPairs[0].folderId); const rng = new SeededRandom(textPairs[0].folderId);
@@ -38,14 +42,7 @@ const Memorize: React.FC<MemorizeProps> = ({ textPairs }) => {
const getTextPairs = () => disorder ? disorderedTextPairs : textPairs; const getTextPairs = () => disorder ? disorderedTextPairs : textPairs;
return ( const handleIndexClick = () => {
<>
{(getTextPairs().length > 0 && (
<>
<div className="text-center">
<div
className="text-sm text-gray-500"
onClick={() => {
const newIndex = prompt("Input a index number.")?.trim(); const newIndex = prompt("Input a index number.")?.trim();
if ( if (
newIndex && newIndex &&
@@ -55,16 +52,56 @@ const Memorize: React.FC<MemorizeProps> = ({ textPairs }) => {
) { ) {
setIndex(parseInt(newIndex) - 1); setIndex(parseInt(newIndex) - 1);
} }
}} };
>
{index + 1} const handleNext = async () => {
{"/" + getTextPairs().length} if (show === "answer") {
</div> const newIndex = (index + 1) % getTextPairs().length;
<div className={`h-[40dvh] md:px-16 px-4 ${myFont.className}`}> setIndex(newIndex);
{(() => { if (dictation) {
const textPair = getTextPairs()[newIndex];
const language = textPair[reverse ? "language2" : "language1"];
const text = textPair[reverse ? "text2" : "text1"];
// 映射语言到 TTS 支持的格式
const languageMap: Record<string, TTS_SUPPORTED_LANGUAGES> = {
"chinese": "Chinese",
"english": "English",
"japanese": "Japanese",
"korean": "Korean",
"french": "French",
"german": "German",
"italian": "Italian",
"portuguese": "Portuguese",
"spanish": "Spanish",
"russian": "Russian",
};
const ttsLanguage = languageMap[language?.toLowerCase()] || "Auto";
getTTSUrl(text, ttsLanguage).then((url) => {
load(url);
play();
});
}
}
setShow(show === "question" ? "answer" : "question");
};
const handlePrevious = () => {
setIndex(
(index - 1 + getTextPairs().length) % getTextPairs().length,
);
setShow("question");
};
const toggleReverse = () => setReverse(!reverse);
const toggleDictation = () => setDictation(!dictation);
const toggleDisorder = () => setDisorder(!disorder);
const createText = (text: string) => { const createText = (text: string) => {
return ( return (
<div className="text-gray-900 text-xl border-y border-y-gray-200 p-4 md:text-3xl h-[20dvh] overflow-y-auto"> <div className="text-gray-900 text-xl md:text-2xl p-6 h-[20dvh] overflow-y-auto text-center">
{text} {text}
</div> </div>
); );
@@ -74,100 +111,85 @@ const Memorize: React.FC<MemorizeProps> = ({ textPairs }) => {
? [getTextPairs()[index].text2, getTextPairs()[index].text1] ? [getTextPairs()[index].text2, getTextPairs()[index].text1]
: [getTextPairs()[index].text1, getTextPairs()[index].text2]; : [getTextPairs()[index].text1, getTextPairs()[index].text2];
return (
<PageLayout>
{/* 进度指示器 */}
<div className="flex justify-center mb-4">
<LinkButton onClick={handleIndexClick} className="text-sm">
{index + 1} / {getTextPairs().length}
</LinkButton>
</div>
{/* 文本显示区域 */}
<div className={`h-[40dvh] ${myFont.className} mb-4`}>
{(() => {
if (dictation) { if (dictation) {
// dictation
if (show === "question") { if (show === "question") {
return createText(""); return (
<div className="h-full flex items-center justify-center">
<div className="text-gray-400 text-4xl">?</div>
</div>
);
} else { } else {
return ( return (
<> <div className="space-y-2">
{createText(text1)} {createText(text1)}
<div className="border-t border-gray-200"></div>
{createText(text2)} {createText(text2)}
</> </div>
); );
} }
} else { } else {
// non-dictation
if (show === "question") { if (show === "question") {
return createText(text1); return createText(text1);
} else { } else {
return ( return (
<> <div className="space-y-2">
{createText(text1)} {createText(text1)}
<div className="border-t border-gray-200"></div>
{createText(text2)} {createText(text2)}
</> </div>
); );
} }
} }
})()} })()}
</div> </div>
</div>
{/* 底部按钮 */}
<div className="flex flex-row gap-2 items-center justify-center flex-wrap"> <div className="flex flex-row gap-2 items-center justify-center flex-wrap">
<LightButton <LightButton
className="w-20" onClick={handleNext}
onClick={async () => { className="px-4 py-2 rounded-full text-sm"
if (show === "answer") {
const newIndex = (index + 1) % getTextPairs().length;
setIndex(newIndex);
if (dictation)
getTTSAudioUrl(
getTextPairs()[newIndex][reverse ? "text2" : "text1"],
VOICES.find(
(v) =>
v.locale ===
getTextPairs()[newIndex][
reverse ? "locale2" : "locale1"
],
)!.short_name,
).then((url) => {
load(url);
play();
});
}
setShow(show === "question" ? "answer" : "question");
}}
> >
{show === "question" ? t("answer") : t("next")} {show === "question" ? t("answer") : t("next")}
</LightButton> </LightButton>
<LightButton <LightButton
onClick={() => { onClick={handlePrevious}
setIndex( className="px-4 py-2 rounded-full text-sm"
(index - 1 + getTextPairs().length) % getTextPairs().length,
);
setShow("question");
}}
> >
{t("previous")} {t("previous")}
</LightButton> </LightButton>
<LightButton <CircleToggleButton
onClick={() => {
setReverse(!reverse);
}}
selected={reverse} selected={reverse}
onClick={toggleReverse}
> >
{t("reverse")} {t("reverse")}
</LightButton> </CircleToggleButton>
<LightButton <CircleToggleButton
onClick={() => {
setDictation(!dictation);
}}
selected={dictation} selected={dictation}
onClick={toggleDictation}
> >
{t("dictation")} {t("dictation")}
</LightButton> </CircleToggleButton>
<LightButton <CircleToggleButton
onClick={() => {
setDisorder(!disorder);
}}
selected={disorder} selected={disorder}
onClick={toggleDisorder}
> >
{t("disorder")} {t("disorder")}
</LightButton> </CircleToggleButton>
</div> </div>
</> </PageLayout>
)) || <p>{t("noTextPairs")}</p>}
</>
); );
}; };
export default Memorize; export { Memorize };

View File

@@ -1,33 +1,19 @@
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server"; import { getTranslations } from "next-intl/server";
import { import { isNonNegativeInteger } from "@/utils/random";
getFoldersWithTotalPairsByUserId, import { FolderSelector } from "./FolderSelector";
getUserIdByFolderId, import { Memorize } from "./Memorize";
} from "@/lib/server/services/folderService";
import { isNonNegativeInteger } from "@/lib/utils";
import FolderSelector from "./FolderSelector";
import Memorize from "./Memorize";
import { getPairsByFolderId } from "@/lib/server/services/pairService";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { actionGetFoldersWithTotalPairsByUserId, actionGetPairsByFolderId } from "@/modules/folder/folder-aciton";
export default async function MemorizePage({ export default async function MemorizePage({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ folder_id?: string; }>; searchParams: Promise<{ folder_id?: string; }>;
}) { }) {
const session = await auth.api.getSession({ headers: await headers() });
const tParam = (await searchParams).folder_id; const tParam = (await searchParams).folder_id;
if (!session) {
redirect(
`/auth?redirect=/memorize${(await searchParams).folder_id
? `?folder_id=${tParam}`
: ""
}`,
);
}
const t = await getTranslations("memorize.page"); const t = await getTranslations("memorize.page");
const folder_id = tParam const folder_id = tParam
@@ -37,17 +23,15 @@ export default async function MemorizePage({
: null; : null;
if (!folder_id) { if (!folder_id) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/auth?redirect=/memorize");
return ( return (
<FolderSelector <FolderSelector
folders={await getFoldersWithTotalPairsByUserId(session.user.id)} folders={(await actionGetFoldersWithTotalPairsByUserId(session.user.id)).data!}
/> />
); );
} }
const owner = await getUserIdByFolderId(folder_id); return <Memorize textPairs={(await actionGetPairsByFolderId(folder_id)).data!} />;
if (owner !== session.user.id) {
return <p>{t("unauthorized")}</p>;
}
return <Memorize textPairs={await getPairsByFolderId(folder_id)} />;
} }

View File

@@ -1,4 +1,4 @@
export default function SubtitleDisplay({ subtitle }: { subtitle: string }) { export function SubtitleDisplay({ subtitle }: { subtitle: string }) {
const words = subtitle.match(/\b[\w']+(?:-[\w']+)*\b/g) || []; const words = subtitle.match(/\b[\w']+(?:-[\w']+)*\b/g) || [];
let i = 0; let i = 0;
return ( return (

View File

@@ -1,6 +1,7 @@
import { useState, useRef, forwardRef, useEffect, useCallback } from "react"; import { useState, useRef, forwardRef, useEffect, useCallback } from "react";
import SubtitleDisplay from "./SubtitleDisplay"; import { SubtitleDisplay } from "./SubtitleDisplay";
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import { RangeInput } from "@/components/ui/RangeInput";
import { getIndex, parseSrt, getNearistIndex } from "../subtitle"; import { getIndex, parseSrt, getNearistIndex } from "../subtitle";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
@@ -196,15 +197,18 @@ const VideoPanel = forwardRef<HTMLVideoElement, VideoPanelProps>(
{t("autoPause", { enabled: autoPause ? "Yes" : "No" })} {t("autoPause", { enabled: autoPause ? "Yes" : "No" })}
</LightButton> </LightButton>
</div> </div>
<input <RangeInput
className="seekbar" className="seekbar"
type="range"
min={0} min={0}
max={srtLength} max={srtLength}
onChange={handleSeek} onChange={(value) => {
step={1} if (videoRef.current && parsedSrtRef.current) {
videoRef.current.currentTime = parsedSrtRef.current[value]?.start || 0;
setProgress(value);
}
}}
value={progress} value={progress}
></input> />
<span>{spanText}</span> <span>{spanText}</span>
</div> </div>
); );
@@ -213,4 +217,4 @@ const VideoPanel = forwardRef<HTMLVideoElement, VideoPanelProps>(
VideoPanel.displayName = "VideoPanel"; VideoPanel.displayName = "VideoPanel";
export default VideoPanel; export { VideoPanel };

View File

@@ -1,13 +1,14 @@
"use client"; "use client";
import React, { useRef } from "react"; import React, { useRef } from "react";
import { Button } from "@/design-system/base/button";
import { FileInputProps } from "../../types/controls"; import { FileInputProps } from "../../types/controls";
interface FileInputComponentProps extends FileInputProps { interface FileInputComponentProps extends FileInputProps {
children: React.ReactNode; children: React.ReactNode;
} }
export default function FileInput({ accept, onFileSelect, disabled, className, children }: FileInputComponentProps) { export function FileInput({ accept, onFileSelect, disabled, className, children }: FileInputComponentProps) {
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const handleClick = React.useCallback(() => { const handleClick = React.useCallback(() => {
@@ -33,13 +34,15 @@ export default function FileInput({ accept, onFileSelect, disabled, className, c
disabled={disabled} disabled={disabled}
className="hidden" className="hidden"
/> />
<button <Button
onClick={handleClick} onClick={handleClick}
disabled={disabled} disabled={disabled}
className={`px-2 py-1 rounded shadow font-bold hover:cursor-pointer hover:bg-gray-200 text-gray-800 bg-white ${disabled ? 'opacity-50 cursor-not-allowed' : ''} ${className || ''}`} variant="secondary"
size="sm"
className={className}
> >
{children} {children}
</button> </Button>
</> </>
); );
} }

View File

@@ -2,10 +2,10 @@
import React from "react"; import React from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import { PlayButtonProps } from "../../types/player"; import { PlayButtonProps } from "../../types/player";
export default function PlayButton({ isPlaying, onToggle, disabled, className }: PlayButtonProps) { export function PlayButton({ isPlaying, onToggle, disabled, className }: PlayButtonProps) {
const t = useTranslations("srt_player"); const t = useTranslations("srt_player");
return ( return (

View File

@@ -2,25 +2,16 @@
import React from "react"; import React from "react";
import { SeekBarProps } from "../../types/player"; import { SeekBarProps } from "../../types/player";
import { RangeInput } from "@/components/ui/RangeInput";
export default function SeekBar({ value, max, onChange, disabled, className }: SeekBarProps) { export function SeekBar({ value, max, onChange, disabled, className }: SeekBarProps) {
const handleChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = parseInt(event.target.value);
onChange(newValue);
}, [onChange]);
return ( return (
<input <RangeInput
type="range"
min={0}
max={max}
value={value} value={value}
onChange={handleChange} max={max}
onChange={onChange}
disabled={disabled} disabled={disabled}
className={`w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''} ${className || ''}`} className={className}
style={{
background: `linear-gradient(to right, #374151 0%, #374151 ${(value / max) * 100}%, #e5e7eb ${(value / max) * 100}%, #e5e7eb 100%)`
}}
/> />
); );
} }

View File

@@ -1,11 +1,11 @@
"use client"; "use client";
import React from "react"; import React from "react";
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import { SpeedControlProps } from "../../types/player"; import { SpeedControlProps } from "../../types/player";
import { getPlaybackRateOptions, getPlaybackRateLabel } from "../../utils/timeUtils"; import { getPlaybackRateOptions, getPlaybackRateLabel } from "../../utils/timeUtils";
export default function SpeedControl({ playbackRate, onPlaybackRateChange, disabled, className }: SpeedControlProps) { export function SpeedControl({ playbackRate, onPlaybackRateChange, disabled, className }: SpeedControlProps) {
const speedOptions = getPlaybackRateOptions(); const speedOptions = getPlaybackRateOptions();
const handleSpeedChange = React.useCallback(() => { const handleSpeedChange = React.useCallback(() => {

View File

@@ -3,7 +3,7 @@
import React from "react"; import React from "react";
import { SubtitleTextProps } from "../../types/subtitle"; import { SubtitleTextProps } from "../../types/subtitle";
export default function SubtitleText({ text, onWordClick, style, className }: SubtitleTextProps) { export function SubtitleText({ text, onWordClick, style, className }: SubtitleTextProps) {
const handleWordClick = React.useCallback((word: string) => { const handleWordClick = React.useCallback((word: string) => {
onWordClick?.(word); onWordClick?.(word);
}, [onWordClick]); }, [onWordClick]);

View File

@@ -46,4 +46,4 @@ const VideoElement = forwardRef<HTMLVideoElement, VideoElementProps>(
VideoElement.displayName = "VideoElement"; VideoElement.displayName = "VideoElement";
export default VideoElement; export { VideoElement };

View File

@@ -3,12 +3,12 @@
import React from "react"; import React from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { ChevronLeft, ChevronRight, RotateCcw, Pause } from "lucide-react"; import { ChevronLeft, ChevronRight, RotateCcw, Pause } from "lucide-react";
import DarkButton from "@/components/ui/buttons/DarkButton"; import { LightButton } from "@/design-system/base/button";
import { ControlBarProps } from "../../types/controls"; import { ControlBarProps } from "../../types/controls";
import PlayButton from "../atoms/PlayButton"; import { PlayButton } from "../atoms/PlayButton";
import SpeedControl from "../atoms/SpeedControl"; import { SpeedControl } from "../atoms/SpeedControl";
export default function ControlBar({ export function ControlBar({
isPlaying, isPlaying,
onPlayPause, onPlayPause,
onPrevious, onPrevious,
@@ -31,32 +31,32 @@ export default function ControlBar({
disabled={disabled} disabled={disabled}
/> />
<DarkButton <LightButton
onClick={disabled ? undefined : onPrevious} onClick={disabled ? undefined : onPrevious}
disabled={disabled} disabled={disabled}
className="flex items-center px-3 py-2" className="flex items-center px-3 py-2"
> >
<ChevronLeft className="w-4 h-4 mr-2" /> <ChevronLeft className="w-4 h-4 mr-2" />
{t("previous")} {t("previous")}
</DarkButton> </LightButton>
<DarkButton <LightButton
onClick={disabled ? undefined : onNext} onClick={disabled ? undefined : onNext}
disabled={disabled} disabled={disabled}
className="flex items-center px-3 py-2" className="flex items-center px-3 py-2"
> >
{t("next")} {t("next")}
<ChevronRight className="w-4 h-4 ml-2" /> <ChevronRight className="w-4 h-4 ml-2" />
</DarkButton> </LightButton>
<DarkButton <LightButton
onClick={disabled ? undefined : onRestart} onClick={disabled ? undefined : onRestart}
disabled={disabled} disabled={disabled}
className="flex items-center px-3 py-2" className="flex items-center px-3 py-2"
> >
<RotateCcw className="w-4 h-4 mr-2" /> <RotateCcw className="w-4 h-4 mr-2" />
{t("restart")} {t("restart")}
</DarkButton> </LightButton>
<SpeedControl <SpeedControl
playbackRate={playbackRate} playbackRate={playbackRate}
@@ -64,14 +64,14 @@ export default function ControlBar({
disabled={disabled} disabled={disabled}
/> />
<DarkButton <LightButton
onClick={disabled ? undefined : onAutoPauseToggle} onClick={disabled ? undefined : onAutoPauseToggle}
disabled={disabled} disabled={disabled}
className="flex items-center px-3 py-2" className="flex items-center px-3 py-2"
> >
<Pause className="w-4 h-4 mr-2" /> <Pause className="w-4 h-4 mr-2" />
{t("autoPause", { enabled: autoPause ? t("on") : t("off") })} {t("autoPause", { enabled: autoPause ? t("on") : t("off") })}
</DarkButton> </LightButton>
</div> </div>
); );
} }

View File

@@ -2,9 +2,9 @@
import React from "react"; import React from "react";
import { SubtitleDisplayProps } from "../../types/subtitle"; import { SubtitleDisplayProps } from "../../types/subtitle";
import SubtitleText from "../atoms/SubtitleText"; import { SubtitleText } from "../atoms/SubtitleText";
export default function SubtitleArea({ subtitle, onWordClick, settings, className }: SubtitleDisplayProps) { export function SubtitleArea({ subtitle, onWordClick, settings, className }: SubtitleDisplayProps) {
const handleWordClick = React.useCallback((word: string) => { const handleWordClick = React.useCallback((word: string) => {
// 打开有道词典页面查询单词 // 打开有道词典页面查询单词
window.open( window.open(

View File

@@ -4,11 +4,11 @@ import React from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { toast } from "sonner"; import { toast } from "sonner";
import { Video, FileText } from "lucide-react"; import { Video, FileText } from "lucide-react";
import DarkButton from "@/components/ui/buttons/DarkButton"; import { LightButton } from "@/design-system/base/button";
import { FileUploadProps } from "../../types/controls"; import { FileUploadProps } from "../../types/controls";
import { useFileUpload } from "../../hooks/useFileUpload"; import { useFileUpload } from "../../hooks/useFileUpload";
export default function UploadZone({ onVideoUpload, onSubtitleUpload, className }: FileUploadProps) { export function UploadZone({ onVideoUpload, onSubtitleUpload, className }: FileUploadProps) {
const t = useTranslations("srt_player"); const t = useTranslations("srt_player");
const { uploadVideo, uploadSubtitle } = useFileUpload(); const { uploadVideo, uploadSubtitle } = useFileUpload();
@@ -26,21 +26,21 @@ export default function UploadZone({ onVideoUpload, onSubtitleUpload, className
return ( return (
<div className={`flex gap-3 ${className || ''}`}> <div className={`flex gap-3 ${className || ''}`}>
<DarkButton <LightButton
onClick={handleVideoUpload} onClick={handleVideoUpload}
className="flex-1 py-2 px-3 text-sm" className="flex-1 py-2 px-3 text-sm"
> >
<Video className="w-4 h-4 mr-2" /> <Video className="w-4 h-4 mr-2" />
{t("uploadVideo")} {t("uploadVideo")}
</DarkButton> </LightButton>
<DarkButton <LightButton
onClick={handleSubtitleUpload} onClick={handleSubtitleUpload}
className="flex-1 py-2 px-3 text-sm" className="flex-1 py-2 px-3 text-sm"
> >
<FileText className="w-4 h-4 mr-2" /> <FileText className="w-4 h-4 mr-2" />
{t("uploadSubtitle")} {t("uploadSubtitle")}
</DarkButton> </LightButton>
</div> </div>
); );
} }

View File

@@ -2,7 +2,7 @@
import React, { forwardRef } from "react"; import React, { forwardRef } from "react";
import { VideoElementProps } from "../../types/player"; import { VideoElementProps } from "../../types/player";
import VideoElement from "../atoms/VideoElement"; import { VideoElement } from "../atoms/VideoElement";
interface VideoPlayerComponentProps extends VideoElementProps { interface VideoPlayerComponentProps extends VideoElementProps {
children?: React.ReactNode; children?: React.ReactNode;
@@ -38,4 +38,4 @@ const VideoPlayer = forwardRef<HTMLVideoElement, VideoPlayerComponentProps>(
VideoPlayer.displayName = "VideoPlayer"; VideoPlayer.displayName = "VideoPlayer";
export default VideoPlayer; export { VideoPlayer };

View File

@@ -4,17 +4,18 @@ import React from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { toast } from "sonner"; import { toast } from "sonner";
import { Video, FileText } from "lucide-react"; import { Video, FileText } from "lucide-react";
import { PageLayout } from "@/components/ui/PageLayout";
import { useSrtPlayer } from "./hooks/useSrtPlayer"; import { useSrtPlayer } from "./hooks/useSrtPlayer";
import { useSubtitleSync } from "./hooks/useSubtitleSync"; import { useSubtitleSync } from "./hooks/useSubtitleSync";
import { useKeyboardShortcuts, createSrtPlayerShortcuts } from "./hooks/useKeyboardShortcuts"; import { useKeyboardShortcuts, createSrtPlayerShortcuts } from "./hooks/useKeyboardShortcuts";
import { useFileUpload } from "./hooks/useFileUpload"; import { useFileUpload } from "./hooks/useFileUpload";
import { loadSubtitle } from "./utils/subtitleParser"; import { loadSubtitle } from "./utils/subtitleParser";
import VideoPlayer from "./components/compounds/VideoPlayer"; import { VideoPlayer } from "./components/compounds/VideoPlayer";
import SubtitleArea from "./components/compounds/SubtitleArea"; import { SubtitleArea } from "./components/compounds/SubtitleArea";
import ControlBar from "./components/compounds/ControlBar"; import { ControlBar } from "./components/compounds/ControlBar";
import UploadZone from "./components/compounds/UploadZone"; import { UploadZone } from "./components/compounds/UploadZone";
import SeekBar from "./components/atoms/SeekBar"; import { SeekBar } from "./components/atoms/SeekBar";
import DarkButton from "@/components/ui/buttons/DarkButton"; import { LightButton } from "@/design-system/base/button";
export default function SrtPlayerPage() { export default function SrtPlayerPage() {
const t = useTranslations("home"); const t = useTranslations("home");
@@ -106,9 +107,7 @@ export default function SrtPlayerPage() {
const canPlay = state.video.url && state.subtitle.url && state.subtitle.data.length > 0; const canPlay = state.video.url && state.subtitle.url && state.subtitle.data.length > 0;
return ( return (
<div className="min-h-screen bg-gray-50"> <PageLayout>
<div className="container mx-auto px-4 py-8">
<div className="max-w-6xl mx-auto">
{/* 标题区域 */} {/* 标题区域 */}
<div className="text-center mb-8"> <div className="text-center mb-8">
<h1 className="text-4xl font-bold text-gray-800 mb-2"> <h1 className="text-4xl font-bold text-gray-800 mb-2">
@@ -119,10 +118,8 @@ export default function SrtPlayerPage() {
</p> </p>
</div> </div>
{/* 主要内容区域 */}
<div className="bg-white rounded-xl shadow-lg overflow-hidden">
{/* 视频播放器区域 */} {/* 视频播放器区域 */}
<div className="aspect-video bg-black relative"> <div className="aspect-video bg-black relative rounded-md overflow-hidden">
{(!state.video.url || !state.subtitle.url || state.subtitle.data.length === 0) && ( {(!state.video.url || !state.subtitle.url || state.subtitle.data.length === 0) && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-900 bg-opacity-75 z-10"> <div className="absolute inset-0 flex items-center justify-center bg-gray-900 bg-opacity-75 z-10">
<div className="text-center text-white"> <div className="text-center text-white">
@@ -164,7 +161,7 @@ export default function SrtPlayerPage() {
</div> </div>
{/* 控制面板 */} {/* 控制面板 */}
<div className="p-3 bg-gray-50 border-t"> <div className="p-3 bg-gray-50 border-t rounded-b-xl">
{/* 上传区域和状态指示器 */} {/* 上传区域和状态指示器 */}
<div className="mb-3"> <div className="mb-3">
<div className="flex gap-3"> <div className="flex gap-3">
@@ -182,13 +179,13 @@ export default function SrtPlayerPage() {
</p> </p>
</div> </div>
</div> </div>
<DarkButton <LightButton
onClick={state.video.url ? undefined : handleVideoUpload} onClick={state.video.url ? undefined : handleVideoUpload}
disabled={!!state.video.url} disabled={!!state.video.url}
className="px-2 py-1 text-xs" className="px-2 py-1 text-xs"
> >
{state.video.url ? srtT("uploaded") : srtT("upload")} {state.video.url ? srtT("uploaded") : srtT("upload")}
</DarkButton> </LightButton>
</div> </div>
</div> </div>
@@ -206,13 +203,13 @@ export default function SrtPlayerPage() {
</p> </p>
</div> </div>
</div> </div>
<DarkButton <LightButton
onClick={state.subtitle.url ? undefined : handleSubtitleUpload} onClick={state.subtitle.url ? undefined : handleSubtitleUpload}
disabled={!!state.subtitle.url} disabled={!!state.subtitle.url}
className="px-2 py-1 text-xs" className="px-2 py-1 text-xs"
> >
{state.subtitle.url ? srtT("uploaded") : srtT("upload")} {state.subtitle.url ? srtT("uploaded") : srtT("upload")}
</DarkButton> </LightButton>
</div> </div>
</div> </div>
</div> </div>
@@ -272,9 +269,6 @@ export default function SrtPlayerPage() {
</div> </div>
</div> </div>
</div> </div>
</div> </PageLayout>
</div>
</div>
</div>
); );
} }

View File

@@ -93,7 +93,7 @@ export async function loadSubtitle(url: string): Promise<SubtitleEntry[]> {
const data = await response.text(); const data = await response.text();
return parseSrt(data); return parseSrt(data);
} catch (error) { } catch (error) {
console.error('Failed to load subtitle:', error); console.error('加载字幕失败', error);
return []; return [];
} }
} }

View File

@@ -6,8 +6,8 @@ import {
TextSpeakerArraySchema, TextSpeakerArraySchema,
TextSpeakerItemSchema, TextSpeakerItemSchema,
} from "@/lib/interfaces"; } from "@/lib/interfaces";
import IconClick from "@/components/ui/buttons/IconClick"; import { IconClick } from "@/design-system/base/button";
import IMAGES from "@/config/images"; import { IMAGES } from "@/config/images";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { getLocalStorageOperator } from "@/lib/browser/localStorageOperators"; import { getLocalStorageOperator } from "@/lib/browser/localStorageOperators";
@@ -24,7 +24,7 @@ function TextCard({ item, handleUse, handleDel }: TextCardProps) {
handleDel(item); handleDel(item);
}; };
return ( return (
<div className="p-2 border-b border-gray-200 rounded-2xl bg-gray-100 m-2 grid grid-cols-8"> <div className="p-2 border-b border-gray-200 rounded-lg bg-gray-100 m-2 grid grid-cols-8">
<div className="col-span-7" onClick={onUseClick}> <div className="col-span-7" onClick={onUseClick}>
<div className="max-h-26 hover:cursor-pointer text-3xl overflow-y-auto"> <div className="max-h-26 hover:cursor-pointer text-3xl overflow-y-auto">
{item.text} {item.text}
@@ -39,7 +39,7 @@ function TextCard({ item, handleUse, handleDel }: TextCardProps) {
alt="delete" alt="delete"
onClick={onDelClick} onClick={onDelClick}
className="place-self-center" className="place-self-center"
size={42} size="lg"
></IconClick> ></IconClick>
</div> </div>
</div> </div>
@@ -50,7 +50,7 @@ interface SaveListProps {
show?: boolean; show?: boolean;
handleUse: (item: z.infer<typeof TextSpeakerItemSchema>) => void; handleUse: (item: z.infer<typeof TextSpeakerItemSchema>) => void;
} }
export default function SaveList({ show = false, handleUse }: SaveListProps) { export function SaveList({ show = false, handleUse }: SaveListProps) {
const t = useTranslations("text_speaker"); const t = useTranslations("text_speaker");
const { get: getFromLocalStorage, set: setIntoLocalStorage } = const { get: getFromLocalStorage, set: setIntoLocalStorage } =
getLocalStorageOperator<typeof TextSpeakerArraySchema>( getLocalStorageOperator<typeof TextSpeakerArraySchema>(
@@ -81,7 +81,7 @@ export default function SaveList({ show = false, handleUse }: SaveListProps) {
if (show) if (show)
return ( return (
<div <div
className="my-4 p-2 mx-4 md:mx-32 border border-gray-200 rounded-2xl" className="my-4 p-2 mx-4 md:mx-32 border border-gray-200 rounded-lg"
style={{ fontFamily: "Times New Roman, serif" }} style={{ fontFamily: "Times New Roman, serif" }}
> >
<div className="flex flex-row justify-center gap-8 items-center"> <div className="flex flex-row justify-center gap-8 items-center">
@@ -89,14 +89,14 @@ export default function SaveList({ show = false, handleUse }: SaveListProps) {
src={IMAGES.refresh} src={IMAGES.refresh}
alt="refresh" alt="refresh"
onClick={refresh} onClick={refresh}
size={48} size="lg"
className="" className=""
></IconClick> ></IconClick>
<IconClick <IconClick
src={IMAGES.delete} src={IMAGES.delete}
alt="delete" alt="delete"
onClick={handleDeleteAll} onClick={handleDeleteAll}
size={48} size="lg"
className="" className=""
></IconClick> ></IconClick>
</div> </div>

View File

@@ -1,8 +1,8 @@
"use client"; "use client";
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import IconClick from "@/components/ui/buttons/IconClick"; import { IconClick } from "@/design-system/base/button";
import IMAGES from "@/config/images"; import { IMAGES } from "@/config/images";
import { useAudioPlayer } from "@/hooks/useAudioPlayer"; import { useAudioPlayer } from "@/hooks/useAudioPlayer";
import { import {
TextSpeakerArraySchema, TextSpeakerArraySchema,
@@ -10,13 +10,13 @@ import {
} from "@/lib/interfaces"; } from "@/lib/interfaces";
import { ChangeEvent, useEffect, useRef, useState } from "react"; import { ChangeEvent, useEffect, useRef, useState } from "react";
import z from "zod"; import z from "zod";
import SaveList from "./SaveList"; import { SaveList } from "./SaveList";
import { VOICES } from "@/config/locales";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { getLocalStorageOperator } from "@/lib/browser/localStorageOperators"; import { getLocalStorageOperator } from "@/lib/browser/localStorageOperators";
import { getTTSAudioUrl } from "@/lib/browser/tts"; import { genIPA, genLanguage } from "@/modules/translator/translator-action";
import { genIPA, genLocale } from "@/lib/server/translatorActions"; import { PageLayout } from "@/components/ui/PageLayout";
import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/bigmodel/tts";
export default function TextSpeakerPage() { export default function TextSpeakerPage() {
const t = useTranslations("text_speaker"); const t = useTranslations("text_speaker");
@@ -29,7 +29,7 @@ export default function TextSpeakerPage() {
const [pause, setPause] = useState(true); const [pause, setPause] = useState(true);
const [autopause, setAutopause] = useState(true); const [autopause, setAutopause] = useState(true);
const textRef = useRef(""); const textRef = useRef("");
const [locale, setLocale] = useState<string | null>(null); const [language, setLanguage] = useState<string | null>(null);
const [ipa, setIPA] = useState<string>(""); const [ipa, setIPA] = useState<string>("");
const objurlRef = useRef<string | null>(null); const objurlRef = useRef<string | null>(null);
const [processing, setProcessing] = useState(false); const [processing, setProcessing] = useState(false);
@@ -74,7 +74,7 @@ export default function TextSpeakerPage() {
setIPA(data.ipa); setIPA(data.ipa);
}) })
.catch((e) => { .catch((e) => {
console.error(e); console.error("生成 IPA 失败", e);
setIPA(""); setIPA("");
}); });
} }
@@ -93,40 +93,35 @@ export default function TextSpeakerPage() {
} else { } else {
// 第一次播放 // 第一次播放
try { try {
let theLocale = locale; let theLanguage = language;
if (!theLocale) { if (!theLanguage) {
console.log("downloading text info"); const tmp_language = await genLanguage(textRef.current.slice(0, 30));
const tmp_locale = await genLocale(textRef.current.slice(0, 30)); setLanguage(tmp_language);
setLocale(tmp_locale); theLanguage = tmp_language;
theLocale = tmp_locale;
} }
const voice = VOICES.find((v) => v.locale.startsWith(theLocale)); theLanguage = theLanguage.toLowerCase().replace(/[^a-z]/g, '').replace(/^./, match => match.toUpperCase());
if (!voice) throw "Voice not found.";
objurlRef.current = await getTTSAudioUrl( // 检查语言是否在 TTS 支持列表中
const supportedLanguages: TTS_SUPPORTED_LANGUAGES[] = [
"Auto", "Chinese", "English", "German", "Italian", "Portuguese",
"Spanish", "Japanese", "Korean", "French", "Russian"
];
if (!supportedLanguages.includes(theLanguage as TTS_SUPPORTED_LANGUAGES)) {
theLanguage = "Auto";
}
objurlRef.current = await getTTSUrl(
textRef.current, textRef.current,
voice.short_name, theLanguage as TTS_SUPPORTED_LANGUAGES
(() => {
if (speed === 1) return {};
else if (speed < 1)
return {
rate: `-${100 - speed * 100}%`,
};
else
return {
rate: `+${speed * 100 - 100}%`,
};
})(),
); );
load(objurlRef.current); load(objurlRef.current);
play(); play();
} catch (e) { } catch (e) {
console.error(e); console.error("播放音频失败", e);
setPause(true); setPause(true);
setLocale(null); setLanguage(null);
setProcessing(false); setProcessing(false);
} }
} }
@@ -142,7 +137,7 @@ export default function TextSpeakerPage() {
const handleInputChange = (e: ChangeEvent<HTMLTextAreaElement>) => { const handleInputChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
textRef.current = e.target.value.trim(); textRef.current = e.target.value.trim();
setLocale(null); setLanguage(null);
setIPA(""); setIPA("");
if (objurlRef.current) URL.revokeObjectURL(objurlRef.current); if (objurlRef.current) URL.revokeObjectURL(objurlRef.current);
objurlRef.current = null; objurlRef.current = null;
@@ -163,7 +158,7 @@ export default function TextSpeakerPage() {
const handleUseItem = (item: z.infer<typeof TextSpeakerItemSchema>) => { const handleUseItem = (item: z.infer<typeof TextSpeakerItemSchema>) => {
if (textareaRef.current) textareaRef.current.value = item.text; if (textareaRef.current) textareaRef.current.value = item.text;
textRef.current = item.text; textRef.current = item.text;
setLocale(item.locale); setLanguage(item.language);
setIPA(item.ipa || ""); setIPA(item.ipa || "");
if (objurlRef.current) URL.revokeObjectURL(objurlRef.current); if (objurlRef.current) URL.revokeObjectURL(objurlRef.current);
objurlRef.current = null; objurlRef.current = null;
@@ -178,12 +173,11 @@ export default function TextSpeakerPage() {
setSaving(true); setSaving(true);
try { try {
let theLocale = locale; let theLanguage = language;
if (!theLocale) { if (!theLanguage) {
console.log("downloading text info"); const tmp_language = await genLanguage(textRef.current.slice(0, 30));
const tmp_locale = await genLocale(textRef.current.slice(0, 30)); setLanguage(tmp_language);
setLocale(tmp_locale); theLanguage = tmp_language;
theLocale = tmp_locale;
} }
let theIPA = ipa; let theIPA = ipa;
@@ -206,73 +200,79 @@ export default function TextSpeakerPage() {
} else if (theIPA.length === 0) { } else if (theIPA.length === 0) {
save.push({ save.push({
text: textRef.current, text: textRef.current,
locale: theLocale, language: theLanguage as string,
}); });
} else { } else {
save.push({ save.push({
text: textRef.current, text: textRef.current,
locale: theLocale, language: theLanguage as string,
ipa: theIPA, ipa: theIPA,
}); });
} }
setIntoLocalStorage(save); setIntoLocalStorage(save);
} catch (e) { } catch (e) {
console.error(e); console.error("保存到本地存储失败", e);
setLocale(null); setLanguage(null);
} finally { } finally {
setSaving(false); setSaving(false);
} }
}; };
return ( return (
<> <PageLayout className="items-start py-4">
{/* 文本输入区域 */}
<div <div
className="my-4 p-4 mx-4 md:mx-32 border border-gray-200 rounded-2xl" className="border border-gray-200 rounded-lg"
style={{ fontFamily: "Times New Roman, serif" }} style={{ fontFamily: "Times New Roman, serif" }}
> >
{/* 文本输入框 */}
<textarea <textarea
className="text-2xl resize-none focus:outline-0 min-h-64 w-full border-gray-200 border-b" className="text-2xl resize-none focus:outline-0 min-h-64 w-full border-gray-200 border-b p-4"
onChange={handleInputChange} onChange={handleInputChange}
ref={textareaRef} ref={textareaRef}
></textarea> ></textarea>
{/* IPA 显示区域 */}
{(ipa.length !== 0 && ( {(ipa.length !== 0 && (
<div className="overflow-auto text-gray-600 h-18 border-gray-200 border-b"> <div className="overflow-auto text-gray-600 h-18 border-gray-200 border-b px-4">
{ipa} {ipa}
</div> </div>
)) || <div className="h-18"></div>} )) || <div className="h-18"></div>}
<div className="mt-8 relative w-full flex flex-row flex-wrap gap-2 justify-center items-center">
{/* 控制按钮区域 */}
<div className="p-4 relative w-full flex flex-row flex-wrap gap-2 justify-center items-center">
{/* 速度调节面板 */}
{showSpeedAdjust && ( {showSpeedAdjust && (
<div className="bg-white p-6 rounded-2xl border-gray-200 border-2 shadow-2xl absolute left-1/2 -translate-x-1/2 -translate-y-full -top-4 flex flex-row flex-wrap gap-2 justify-center items-center"> <div className="bg-white p-6 rounded-lg border-gray-200 border-2 shadow-2xl absolute left-1/2 -translate-x-1/2 -translate-y-full -top-4 flex flex-row flex-wrap gap-2 justify-center items-center z-10">
<IconClick <IconClick
size={45} size="lg"
onClick={letMeSetSpeed(0.5)} onClick={letMeSetSpeed(0.5)}
src={IMAGES.speed_0_5x} src={IMAGES.speed_0_5x}
alt="0.5x" alt="0.5x"
className={speed === 0.5 ? "bg-gray-200" : ""} className={speed === 0.5 ? "bg-gray-200" : ""}
></IconClick> ></IconClick>
<IconClick <IconClick
size={45} size="lg"
onClick={letMeSetSpeed(0.7)} onClick={letMeSetSpeed(0.7)}
src={IMAGES.speed_0_7x} src={IMAGES.speed_0_7x}
alt="0.7x" alt="0.7x"
className={speed === 0.7 ? "bg-gray-200" : ""} className={speed === 0.7 ? "bg-gray-200" : ""}
></IconClick> ></IconClick>
<IconClick <IconClick
size={45} size="lg"
onClick={letMeSetSpeed(1)} onClick={letMeSetSpeed(1)}
src={IMAGES.speed_1x} src={IMAGES.speed_1x}
alt="1x" alt="1x"
className={speed === 1 ? "bg-gray-200" : ""} className={speed === 1 ? "bg-gray-200" : ""}
></IconClick> ></IconClick>
<IconClick <IconClick
size={45} size="lg"
onClick={letMeSetSpeed(1.2)} onClick={letMeSetSpeed(1.2)}
src={IMAGES.speed_1_2_x} src={IMAGES.speed_1_2_x}
alt="1.2x" alt="1.2x"
className={speed === 1.2 ? "bg-gray-200" : ""} className={speed === 1.2 ? "bg-gray-200" : ""}
></IconClick> ></IconClick>
<IconClick <IconClick
size={45} size="lg"
onClick={letMeSetSpeed(1.5)} onClick={letMeSetSpeed(1.5)}
src={IMAGES.speed_1_5x} src={IMAGES.speed_1_5x}
alt="1.5x" alt="1.5x"
@@ -280,15 +280,17 @@ export default function TextSpeakerPage() {
></IconClick> ></IconClick>
</div> </div>
)} )}
{/* 播放/暂停按钮 */}
<IconClick <IconClick
size={45} size="lg"
onClick={speak} onClick={speak}
src={pause ? IMAGES.play_arrow : IMAGES.pause} src={pause ? IMAGES.play_arrow : IMAGES.pause}
alt="playorpause" alt="playorpause"
className={`${processing ? "bg-gray-200" : ""}`} className={`${processing ? "bg-gray-200" : ""}`}
></IconClick> ></IconClick>
{/* 自动暂停按钮 */}
<IconClick <IconClick
size={45} size="lg"
onClick={() => { onClick={() => {
setAutopause(!autopause); setAutopause(!autopause);
if (objurlRef) { if (objurlRef) {
@@ -299,20 +301,23 @@ export default function TextSpeakerPage() {
src={autopause ? IMAGES.autoplay : IMAGES.autopause} src={autopause ? IMAGES.autoplay : IMAGES.autopause}
alt="autoplayorpause" alt="autoplayorpause"
></IconClick> ></IconClick>
{/* 速度调节按钮 */}
<IconClick <IconClick
size={45} size="lg"
onClick={() => setShowSpeedAdjust(!showSpeedAdjust)} onClick={() => setShowSpeedAdjust(!showSpeedAdjust)}
src={IMAGES.speed} src={IMAGES.speed}
alt="speed" alt="speed"
className={`${showSpeedAdjust ? "bg-gray-200" : ""}`} className={`${showSpeedAdjust ? "bg-gray-200" : ""}`}
></IconClick> ></IconClick>
{/* 保存按钮 */}
<IconClick <IconClick
size={45} size="lg"
onClick={save} onClick={save}
src={IMAGES.save} src={IMAGES.save}
alt="save" alt="save"
className={`${saving ? "bg-gray-200" : ""}`} className={`${saving ? "bg-gray-200" : ""}`}
></IconClick> ></IconClick>
{/* 功能开关按钮 */}
<div className="w-full flex flex-row flex-wrap gap-2 justify-center items-center"> <div className="w-full flex flex-row flex-wrap gap-2 justify-center items-center">
<LightButton <LightButton
selected={ipaEnabled} selected={ipaEnabled}
@@ -331,7 +336,12 @@ export default function TextSpeakerPage() {
</div> </div>
</div> </div>
</div> </div>
{/* 保存列表 */}
{showSaveList && (
<div className="mt-4 border border-gray-200 rounded-lg overflow-hidden">
<SaveList show={showSaveList} handleUse={handleUseItem}></SaveList> <SaveList show={showSaveList} handleUse={handleUseItem}></SaveList>
</> </div>
)}
</PageLayout>
); );
} }

View File

@@ -1,88 +0,0 @@
"use client";
import LightButton from "@/components/ui/buttons/LightButton";
import Container from "@/components/ui/Container";
import { TranslationHistorySchema } from "@/lib/interfaces";
import { Dispatch, useEffect, useState } from "react";
import z from "zod";
import { Folder } from "../../../../generated/prisma/browser";
import { getFoldersByUserId } from "@/lib/server/services/folderService";
import { Folder as Fd } from "lucide-react";
import { createPair } from "@/lib/server/services/pairService";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { authClient } from "@/lib/auth-client";
interface AddToFolderProps {
item: z.infer<typeof TranslationHistorySchema>;
setShow: Dispatch<React.SetStateAction<boolean>>;
}
const AddToFolder: React.FC<AddToFolderProps> = ({ item, setShow }) => {
const { data: session } = authClient.useSession();
const [folders, setFolders] = useState<Folder[]>([]);
const t = useTranslations("translator.add_to_folder");
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!session) return;
const userId = session.user.id;
getFoldersByUserId(userId)
.then(setFolders)
.then(() => setLoading(false));
}, [session]);
if (!session) {
return (
<div className="fixed left-0 top-0 z-50 w-screen h-screen bg-black/50 flex justify-center items-center">
<Container className="p-6">
<div>{t("notAuthenticated")}</div>
</Container>
</div>
);
}
return (
<div className="fixed left-0 top-0 z-50 w-screen h-screen bg-black/50 flex justify-center items-center">
<Container className="p-6">
<h1>{t("chooseFolder")}</h1>
<div className="border border-gray-200 rounded-2xl">
{(loading && <span>...</span>) ||
(folders.length > 0 &&
folders.map((folder) => (
<button
key={folder.id}
className="p-2 flex items-center justify-start hover:bg-gray-50 gap-2 hover:cursor-pointer w-full border-b border-gray-200"
onClick={() => {
createPair({
text1: item.text1,
text2: item.text2,
locale1: item.locale1,
locale2: item.locale2,
folder: {
connect: {
id: folder.id,
},
},
})
.then(() => {
toast.success(t("success"));
setShow(false);
})
.catch(() => {
toast.error(t("error"));
});
}}
>
<Fd />
{t("folderInfo", { id: folder.id, name: folder.name })}
</button>
))) || <div>{t("noFolders")}</div>}
</div>
<LightButton onClick={() => setShow(false)}>{t("close")}</LightButton>
</Container>
</div>
);
};
export default AddToFolder;

View File

@@ -1,57 +0,0 @@
import Container from "@/components/ui/Container";
import { useEffect, useState } from "react";
import { Folder } from "../../../../generated/prisma/browser";
import { getFoldersByUserId } from "@/lib/server/services/folderService";
import LightButton from "@/components/ui/buttons/LightButton";
import { Folder as Fd } from "lucide-react";
interface FolderSelectorProps {
setSelectedFolderId: (id: number) => void;
userId: string;
cancel: () => void;
}
const FolderSelector: React.FC<FolderSelectorProps> = ({
setSelectedFolderId,
userId,
cancel,
}) => {
const [loading, setLoading] = useState(false);
const [folders, setFolders] = useState<Folder[]>([]);
useEffect(() => {
getFoldersByUserId(userId)
.then(setFolders)
.then(() => setLoading(false));
}, [userId]);
return (
<div
className={`bg-black/50 fixed inset-0 z-50 flex justify-center items-center`}
>
<Container className="p-6">
{(loading && <p>Loading...</p>) ||
(folders.length > 0 && (
<>
<h1>Select a Folder</h1>
<div className="m-2 border-gray-200 border rounded-2xl max-h-96 overflow-y-auto">
{folders.map((folder) => (
<button
className="p-2 w-full flex hover:bg-gray-50 gap-2"
key={folder.id}
onClick={() => setSelectedFolderId(folder.id)}
>
<Fd />
{folder.id}. {folder.name}
</button>
))}
</div>
</>
)) || <p>No folders found</p>}
<LightButton onClick={cancel}>Cancel</LightButton>
</Container>
</div>
);
};
export default FolderSelector;

View File

@@ -1,191 +1,106 @@
"use client"; "use client";
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton, PrimaryButton, IconClick } from "@/design-system/base/button";
import IconClick from "@/components/ui/buttons/IconClick"; import { IMAGES } from "@/config/images";
import IMAGES from "@/config/images";
import { VOICES } from "@/config/locales";
import { useAudioPlayer } from "@/hooks/useAudioPlayer"; import { useAudioPlayer } from "@/hooks/useAudioPlayer";
import { TranslationHistorySchema } from "@/lib/interfaces";
import { tlsoPush, tlso } from "@/lib/browser/localStorageOperators";
import { getTTSAudioUrl } from "@/lib/browser/tts";
import { Plus, Trash } from "lucide-react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react"; import { useRef, useState } from "react";
import z from "zod"; import { actionTranslateText } from "@/modules/translator/translator-action";
import AddToFolder from "./AddToFolder";
import {
genIPA,
genLocale,
genTranslation,
} from "@/lib/server/translatorActions";
import { toast } from "sonner"; import { toast } from "sonner";
import FolderSelector from "./FolderSelector"; import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/bigmodel/tts";
import { createPair } from "@/lib/server/services/pairService"; import { TSharedTranslationResult } from "@/shared/translator-type";
import { shallowEqual } from "@/lib/utils";
import { authClient } from "@/lib/auth-client";
export default function TranslatorPage() { export default function TranslatorPage() {
const t = useTranslations("translator"); const t = useTranslations("translator");
const taref = useRef<HTMLTextAreaElement>(null); const taref = useRef<HTMLTextAreaElement>(null);
const [lang, setLang] = useState<string>("chinese"); const [targetLanguage, setTargetLanguage] = useState<string>("Chinese");
const [tresult, setTresult] = useState<string>(""); const [translationResult, setTranslationResult] = useState<TSharedTranslationResult | null>(null);
const [genIpa, setGenIpa] = useState(true); const [needIpa, setNeedIpa] = useState(true);
const [ipaTexts, setIpaTexts] = useState(["", ""]);
const [processing, setProcessing] = useState(false); const [processing, setProcessing] = useState(false);
const [lastTranslation, setLastTranslation] = useState<{
sourceText: string;
targetLanguage: string;
} | null>(null);
const { load, play } = useAudioPlayer(); const { load, play } = useAudioPlayer();
const [history, setHistory] = useState<
z.infer<typeof TranslationHistorySchema>[]
>([]);
const [showAddToFolder, setShowAddToFolder] = useState(false);
const [addToFolderItem, setAddToFolderItem] = useState<z.infer<
typeof TranslationHistorySchema
> | null>(null);
const lastTTS = useRef({ const lastTTS = useRef({
text: "", text: "",
url: "", url: "",
}); });
const [autoSave, setAutoSave] = useState(false);
const [autoSaveFolderId, setAutoSaveFolderId] = useState<number | null>(null);
const { data: session } = authClient.useSession();
useEffect(() => {
setHistory(tlso.get());
}, []);
const tts = async (text: string, locale: string) => { const tts = async (text: string, locale: string) => {
if (lastTTS.current.text !== text) { if (lastTTS.current.text !== text) {
const shortName = VOICES.find((v) => v.locale === locale)?.short_name;
if (!shortName) {
toast.error("Voice not found");
return;
}
try { try {
const url = await getTTSAudioUrl(text, shortName); // Map language name to TTS format
let theLanguage = locale.toLowerCase().replace(/[^a-z]/g, '').replace(/^./, match => match.toUpperCase());
// Check if language is in TTS supported list
const supportedLanguages: TTS_SUPPORTED_LANGUAGES[] = [
"Auto", "Chinese", "English", "German", "Italian", "Portuguese",
"Spanish", "Japanese", "Korean", "French", "Russian"
];
if (!supportedLanguages.includes(theLanguage as TTS_SUPPORTED_LANGUAGES)) {
theLanguage = "Auto";
}
const url = await getTTSUrl(text, theLanguage as TTS_SUPPORTED_LANGUAGES);
await load(url); await load(url);
await play();
lastTTS.current.text = text; lastTTS.current.text = text;
lastTTS.current.url = url; lastTTS.current.url = url;
} catch (error) { } catch (error) {
toast.error("Failed to generate audio"); toast.error("Failed to generate audio");
console.error(error);
} }
} }
await play();
}; };
const translate = async () => { const translate = async () => {
if (!taref.current) return; if (!taref.current || processing) return;
if (processing) return;
setProcessing(true); setProcessing(true);
const text1 = taref.current.value; const sourceText = taref.current.value;
const llmres: { // 判断是否需要强制重新翻译
text1: string | null; // 只有当源文本和目标语言都与上次相同时,才强制重新翻译
text2: string | null; const forceRetranslate =
locale1: string | null; lastTranslation?.sourceText === sourceText &&
locale2: string | null; lastTranslation?.targetLanguage === targetLanguage;
ipa1: string | null;
ipa2: string | null;
} = {
text1: text1,
text2: null,
locale1: null,
locale2: null,
ipa1: null,
ipa2: null,
};
let historyUpdated = false; try {
const result = await actionTranslateText({
// 检查更新历史记录 sourceText,
const checkUpdateLocalStorage = () => { targetLanguage,
if (historyUpdated) return; forceRetranslate,
if (llmres.text1 && llmres.text2 && llmres.locale1 && llmres.locale2) { needIpa,
setHistory(
tlsoPush({
text1: llmres.text1,
text2: llmres.text2,
locale1: llmres.locale1,
locale2: llmres.locale2,
}),
);
if (autoSave && autoSaveFolderId) {
createPair({
text1: llmres.text1,
text2: llmres.text2,
locale1: llmres.locale1,
locale2: llmres.locale2,
folder: {
connect: {
id: autoSaveFolderId,
},
},
})
.then(() => {
toast.success(
llmres.text1 + "保存到文件夹" + autoSaveFolderId + "成功",
);
})
.catch((error) => {
toast.error(
llmres.text1 +
"保存到文件夹" +
autoSaveFolderId +
"失败:" +
error.message,
);
}); });
if (result.success && result.data) {
setTranslationResult(result.data);
setLastTranslation({
sourceText,
targetLanguage,
});
} else {
toast.error(result.message || "翻译失败,请重试");
} }
historyUpdated = true; } catch (error) {
} toast.error("翻译失败,请重试");
}; console.error("翻译错误:", error);
// 更新局部翻译状态 } finally {
const updateState = (stateName: keyof typeof llmres, value: string) => {
llmres[stateName] = value;
checkUpdateLocalStorage();
};
genTranslation(text1, lang)
.then(async (text2) => {
updateState("text2", text2);
setTresult(text2);
// 生成两个locale
genLocale(text1).then((locale) => {
updateState("locale1", locale);
});
genLocale(text2).then((locale) => {
updateState("locale2", locale);
});
// 生成俩IPA
if (genIpa) {
genIPA(text1).then((ipa1) => {
setIpaTexts((prev) => [ipa1, prev[1]]);
updateState("ipa1", ipa1);
});
genIPA(text2).then((ipa2) => {
setIpaTexts((prev) => [prev[0], ipa2]);
updateState("ipa2", ipa2);
});
}
})
.catch(() => {
toast.error("Translation failed");
})
.finally(() => {
setProcessing(false); setProcessing(false);
}); }
}; };
return ( return (
<> <div className="min-h-[calc(100vh-64px)] bg-white">
{/* TCard Component */} {/* TCard Component */}
<div className="w-screen flex flex-col md:flex-row md:justify-between gap-2 p-2"> <div className="w-screen flex flex-col md:flex-row md:justify-between gap-2 p-2">
{/* Card Component - Left Side */} {/* Card Component - Left Side */}
<div className="w-full md:w-1/2 flex flex-col-reverse gap-2"> <div className="w-full md:w-1/2 flex flex-col-reverse gap-2">
{/* ICard1 Component */} {/* ICard1 Component */}
<div className="border border-gray-200 rounded-2xl w-full h-64 p-2"> <div className="border border-gray-200 rounded-lg w-full h-64 p-2">
<textarea <textarea
className="resize-none h-8/12 w-full focus:outline-0" className="resize-none h-8/12 w-full focus:outline-0"
ref={taref} ref={taref}
@@ -194,7 +109,7 @@ export default function TranslatorPage() {
}} }}
></textarea> ></textarea>
<div className="ipa w-full h-2/12 overflow-auto text-gray-600"> <div className="ipa w-full h-2/12 overflow-auto text-gray-600">
{ipaTexts[0]} {translationResult?.sourceIpa || ""}
</div> </div>
<div className="h-2/12 w-full flex justify-end items-center"> <div className="h-2/12 w-full flex justify-end items-center">
<IconClick <IconClick
@@ -212,7 +127,7 @@ export default function TranslatorPage() {
onClick={() => { onClick={() => {
const t = taref.current?.value; const t = taref.current?.value;
if (!t) return; if (!t) return;
tts(t, tlso.get().find((v) => v.text1 === t)?.locale1 || ""); tts(t, translationResult?.sourceLanguage || "");
}} }}
></IconClick> ></IconClick>
</div> </div>
@@ -220,8 +135,8 @@ export default function TranslatorPage() {
<div className="option1 w-full flex flex-row justify-between items-center"> <div className="option1 w-full flex flex-row justify-between items-center">
<span>{t("detectLanguage")}</span> <span>{t("detectLanguage")}</span>
<LightButton <LightButton
selected={genIpa} selected={needIpa}
onClick={() => setGenIpa((prev) => !prev)} onClick={() => setNeedIpa((prev) => !prev)}
> >
{t("generateIPA")} {t("generateIPA")}
</LightButton> </LightButton>
@@ -231,26 +146,27 @@ export default function TranslatorPage() {
{/* Card Component - Right Side */} {/* Card Component - Right Side */}
<div className="w-full md:w-1/2 flex flex-col-reverse gap-2"> <div className="w-full md:w-1/2 flex flex-col-reverse gap-2">
{/* ICard2 Component */} {/* ICard2 Component */}
<div className="bg-gray-100 rounded-2xl w-full h-64 p-2"> <div className="bg-gray-100 rounded-lg w-full h-64 p-2">
<div className="h-2/3 w-full overflow-y-auto">{tresult}</div> <div className="h-2/3 w-full overflow-y-auto">{translationResult?.translatedText || ""}</div>
<div className="ipa w-full h-1/6 overflow-y-auto text-gray-600"> <div className="ipa w-full h-1/6 overflow-y-auto text-gray-600">
{ipaTexts[1]} {translationResult?.targetIpa || ""}
</div> </div>
<div className="h-1/6 w-full flex justify-end items-center"> <div className="h-1/6 w-full flex justify-end items-center">
<IconClick <IconClick
src={IMAGES.copy_all} src={IMAGES.copy_all}
alt="copy" alt="copy"
onClick={async () => { onClick={async () => {
await navigator.clipboard.writeText(tresult); await navigator.clipboard.writeText(translationResult?.translatedText || "");
}} }}
></IconClick> ></IconClick>
<IconClick <IconClick
src={IMAGES.play_arrow} src={IMAGES.play_arrow}
alt="play" alt="play"
onClick={() => { onClick={() => {
if (!translationResult) return;
tts( tts(
tresult, translationResult.translatedText,
tlso.get().find((v) => v.text2 === tresult)?.locale2 || "", translationResult.targetLanguage,
); );
}} }}
></IconClick> ></IconClick>
@@ -259,29 +175,29 @@ export default function TranslatorPage() {
<div className="option2 w-full flex gap-1 items-center flex-wrap"> <div className="option2 w-full flex gap-1 items-center flex-wrap">
<span>{t("translateInto")}</span> <span>{t("translateInto")}</span>
<LightButton <LightButton
selected={lang === "chinese"} selected={targetLanguage === "Chinese"}
onClick={() => setLang("chinese")} onClick={() => setTargetLanguage("Chinese")}
> >
{t("chinese")} {t("chinese")}
</LightButton> </LightButton>
<LightButton <LightButton
selected={lang === "english"} selected={targetLanguage === "English"}
onClick={() => setLang("english")} onClick={() => setTargetLanguage("English")}
> >
{t("english")} {t("english")}
</LightButton> </LightButton>
<LightButton <LightButton
selected={lang === "italian"} selected={targetLanguage === "Italian"}
onClick={() => setLang("italian")} onClick={() => setTargetLanguage("Italian")}
> >
{t("italian")} {t("italian")}
</LightButton> </LightButton>
<LightButton <LightButton
selected={!["chinese", "english", "italian"].includes(lang)} selected={!["Chinese", "English", "Italian"].includes(targetLanguage)}
onClick={() => { onClick={() => {
const newLang = prompt(t("enterLanguage")); const newLang = prompt(t("enterLanguage"));
if (newLang) { if (newLang) {
setLang(newLang); setTargetLanguage(newLang);
} }
}} }}
> >
@@ -293,87 +209,15 @@ export default function TranslatorPage() {
{/* TranslateButton Component */} {/* TranslateButton Component */}
<div className="w-screen flex justify-center items-center"> <div className="w-screen flex justify-center items-center">
<button <PrimaryButton
className={`duration-150 ease-in text-xl font-extrabold border rounded-4xl p-3 border-gray-200 h-16 ${processing ? "bg-gray-200" : "bg-white hover:bg-gray-200 hover:cursor-pointer"}`}
onClick={translate} onClick={translate}
disabled={processing}
size="lg"
className="text-xl"
> >
{t("translate")} {t("translate")}
</button> </PrimaryButton>
</div>
{/* AutoSave Component */}
<div className="w-screen flex justify-center items-center">
<label className="flex items-center">
<input
type="checkbox"
checked={autoSave}
onChange={(e) => {
const checked = e.target.checked;
if (checked === true && !session) {
toast.warning("Please login to enable auto-save");
return;
}
if (checked === false) setAutoSaveFolderId(null);
setAutoSave(checked);
}}
className="mr-2"
/>
{t("autoSave")}
{autoSaveFolderId ? ` (${autoSaveFolderId})` : ""}
</label>
</div>
{history.length > 0 && (
<div className="m-6 flex flex-col items-center">
<h1 className="text-2xl font-light">{t("history")}</h1>
<div className="border border-gray-200 rounded-2xl m-4">
{history.toReversed().map((item, index) => (
<div
key={index}
className="border-b border-gray-200 p-2 group hover:bg-gray-50 flex gap-2 flex-row justify-between items-start"
>
<div className="flex-1 flex flex-col">
<p className="text-sm font-light">{item.text1}</p>
<p className="text-sm font-light">{item.text2}</p>
</div>
<div className="flex gap-2">
<button
onClick={() => {
setShowAddToFolder(true);
setAddToFolderItem(item);
}}
className="hover:bg-gray-200 hover:cursor-pointer rounded-4xl border border-gray-200 w-8 h-8 flex justify-center items-center"
>
<Plus />
</button>
<button
onClick={() => {
setHistory(
tlso.set(
tlso.get().filter((v) => !shallowEqual(v, item)),
) || [],
);
}}
className="hover:bg-gray-200 hover:cursor-pointer rounded-4xl border border-gray-200 w-8 h-8 flex justify-center items-center"
>
<Trash />
</button>
</div> </div>
</div> </div>
))}
</div>
{showAddToFolder && (
<AddToFolder setShow={setShowAddToFolder} item={addToFolderItem!} />
)}
{autoSave && !autoSaveFolderId && (
<FolderSelector
userId={session!.user.id as string}
cancel={() => setAutoSave(false)}
setSelectedFolderId={(id) => setAutoSaveFolderId(id)}
/>
)}
</div>
)}
</>
); );
} }

View File

@@ -2,40 +2,39 @@
import { useState, useActionState, startTransition } from "react"; import { useState, useActionState, startTransition } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { signInAction, signUpAction, SignUpState } from "@/lib/actions/auth"; import { PageLayout } from "@/components/ui/PageLayout";
import Container from "@/components/ui/Container"; import { Input } from "@/design-system/base/input";
import Input from "@/components/ui/Input"; import { LightButton, LinkButton } from "@/design-system/base/button";
import LightButton from "@/components/ui/buttons/LightButton";
import DarkButton from "@/components/ui/buttons/DarkButton";
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
import { actionSignIn, actionSignUp, ActionOutputAuth } from "@/modules/auth/auth-action";
interface AuthFormProps { interface AuthFormProps {
redirectTo?: string; redirectTo?: string;
} }
export default function AuthForm({ redirectTo }: AuthFormProps) { export function AuthForm({ redirectTo }: AuthFormProps) {
const t = useTranslations("auth"); const t = useTranslations("auth");
const [mode, setMode] = useState<'signin' | 'signup'>('signin'); const [mode, setMode] = useState<'signin' | 'signup'>('signin');
const [clearSignIn, setClearSignIn] = useState(false); const [clearSignIn, setClearSignIn] = useState(false);
const [clearSignUp, setClearSignUp] = useState(false); const [clearSignUp, setClearSignUp] = useState(false);
const [signInState, signInActionForm, isSignInPending] = useActionState( const [signInState, signInActionForm, isSignInPending] = useActionState(
async (prevState: SignUpState | undefined, formData: FormData) => { async (_prevState: ActionOutputAuth | undefined, formData: FormData) => {
if (clearSignIn) { if (clearSignIn) {
setClearSignIn(false); setClearSignIn(false);
return undefined; return undefined;
} }
return signInAction(prevState || {}, formData); return actionSignIn(undefined, formData);
}, },
undefined undefined
); );
const [signUpState, signUpActionForm, isSignUpPending] = useActionState( const [signUpState, signUpActionForm, isSignUpPending] = useActionState(
async (prevState: SignUpState | undefined, formData: FormData) => { async (_prevState: ActionOutputAuth | undefined, formData: FormData) => {
if (clearSignUp) { if (clearSignUp) {
setClearSignUp(false); setClearSignUp(false);
return undefined; return undefined;
} }
return signUpAction(prevState || {}, formData); return actionSignUp(undefined, formData);
}, },
undefined undefined
); );
@@ -45,17 +44,34 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
const validateForm = (formData: FormData): boolean => { const validateForm = (formData: FormData): boolean => {
const newErrors: Record<string, string> = {}; const newErrors: Record<string, string> = {};
const identifier = formData.get("identifier") as string;
const email = formData.get("email") as string; const email = formData.get("email") as string;
const username = formData.get("username") as string;
const password = formData.get("password") as string; const password = formData.get("password") as string;
const name = formData.get("name") as string;
const confirmPassword = formData.get("confirmPassword") as string; const confirmPassword = formData.get("confirmPassword") as string;
// 登录模式验证
if (mode === 'signin') {
if (!identifier) {
newErrors.identifier = t("identifierRequired");
}
} else {
// 注册模式验证
if (!email) { if (!email) {
newErrors.email = t("emailRequired"); newErrors.email = t("emailRequired");
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
newErrors.email = t("invalidEmail"); newErrors.email = t("invalidEmail");
} }
if (!username) {
newErrors.username = t("usernameRequired");
} else if (username.length < 3) {
newErrors.username = t("usernameTooShort");
} else if (!/^[a-zA-Z0-9_]+$/.test(username)) {
newErrors.username = t("usernameInvalid");
}
}
if (!password) { if (!password) {
newErrors.password = t("passwordRequired"); newErrors.password = t("passwordRequired");
} else if (password.length < 8) { } else if (password.length < 8) {
@@ -63,10 +79,6 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
} }
if (mode === 'signup') { if (mode === 'signup') {
if (!name) {
newErrors.name = t("nameRequired");
}
if (!confirmPassword) { if (!confirmPassword) {
newErrors.confirmPassword = t("confirmPasswordRequired"); newErrors.confirmPassword = t("confirmPasswordRequired");
} else if (password !== confirmPassword) { } else if (password !== confirmPassword) {
@@ -113,36 +125,56 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
const currentError = mode === 'signin' ? signInState : signUpState; const currentError = mode === 'signin' ? signInState : signUpState;
return ( return (
<div className="h-[calc(100vh-64px)] bg-[#35786f] flex items-center justify-center px-4"> <PageLayout>
<Container className="p-8 max-w-md w-full"> {/* 页面标题 */}
<div className="text-center mb-8"> <div className="text-center mb-8">
<h1 className="text-3xl font-bold text-gray-800 mb-2">{t(mode === 'signin' ? 'signIn' : 'signUp')}</h1> <h1 className="text-3xl font-bold text-gray-800 mb-2">{t(mode === 'signin' ? 'signIn' : 'signUp')}</h1>
</div> </div>
{/* 服务器端错误提示 */}
{currentError?.message && ( {currentError?.message && (
<div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded"> <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
{currentError.message} {currentError.message}
</div> </div>
)} )}
{/* 登录/注册表单 */}
<form onSubmit={handleFormSubmit} className="space-y-4"> <form onSubmit={handleFormSubmit} className="space-y-4">
{mode === 'signup' && ( {/* 邮箱/用户名输入(登录模式)或 用户名输入(注册模式) */}
{mode === 'signin' ? (
<div> <div>
<Input <Input
type="text" type="text"
name="name" name="identifier"
placeholder={t("name")} placeholder={t("emailOrUsername")}
className="w-full px-3 py-2" className="w-full px-3 py-2"
/> />
{errors.name && ( {errors.identifier && (
<p className="text-red-500 text-sm mt-1">{errors.name}</p> <p className="text-red-500 text-sm mt-1">{errors.identifier}</p>
)}
{currentError?.errors?.email && (
<p className="text-red-500 text-sm mt-1">{currentError.errors.email[0]}</p>
)}
</div>
) : (
<>
{/* 用户名输入(仅注册模式) */}
<div>
<Input
type="text"
name="username"
placeholder={t("username")}
className="w-full px-3 py-2"
/>
{errors.username && (
<p className="text-red-500 text-sm mt-1">{errors.username}</p>
)} )}
{currentError?.errors?.username && ( {currentError?.errors?.username && (
<p className="text-red-500 text-sm mt-1">{currentError.errors.username[0]}</p> <p className="text-red-500 text-sm mt-1">{currentError.errors.username[0]}</p>
)} )}
</div> </div>
)}
{/* 邮箱输入(仅注册模式) */}
<div> <div>
<Input <Input
type="email" type="email"
@@ -157,7 +189,10 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
<p className="text-red-500 text-sm mt-1">{currentError.errors.email[0]}</p> <p className="text-red-500 text-sm mt-1">{currentError.errors.email[0]}</p>
)} )}
</div> </div>
</>
)}
{/* 密码输入 */}
<div> <div>
<Input <Input
type="password" type="password"
@@ -173,6 +208,7 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
)} )}
</div> </div>
{/* 确认密码输入(仅注册模式显示) */}
{mode === 'signup' && ( {mode === 'signup' && (
<div> <div>
<Input <Input
@@ -187,7 +223,8 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
</div> </div>
)} )}
<DarkButton {/* 提交按钮 */}
<LightButton
type="submit" type="submit"
className={`w-full py-2 ${isSignInPending || isSignUpPending ? 'opacity-50 cursor-not-allowed' : ''}`} className={`w-full py-2 ${isSignInPending || isSignUpPending ? 'opacity-50 cursor-not-allowed' : ''}`}
> >
@@ -195,10 +232,12 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
? t("loading") ? t("loading")
: t(mode === 'signin' ? 'signInButton' : 'signUpButton') : t(mode === 'signin' ? 'signInButton' : 'signUpButton')
} }
</DarkButton> </LightButton>
</form> </form>
{/* 第三方登录区域 */}
<div className="mt-6"> <div className="mt-6">
{/* 分隔线 */}
<div className="relative"> <div className="relative">
<div className="absolute inset-0 flex items-center"> <div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-gray-300"></div> <div className="w-full border-t border-gray-300"></div>
@@ -208,6 +247,7 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
</div> </div>
</div> </div>
{/* GitHub 登录按钮 */}
<LightButton <LightButton
onClick={handleGitHubSignIn} onClick={handleGitHubSignIn}
className="w-full mt-4 py-2 flex items-center justify-center gap-2" className="w-full mt-4 py-2 flex items-center justify-center gap-2"
@@ -219,8 +259,9 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
</LightButton> </LightButton>
</div> </div>
{/* 模式切换链接 */}
<div className="mt-6 text-center"> <div className="mt-6 text-center">
<button <LinkButton
type="button" type="button"
onClick={() => { onClick={() => {
setMode(mode === 'signin' ? 'signup' : 'signin'); setMode(mode === 'signin' ? 'signup' : 'signin');
@@ -232,15 +273,13 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
setClearSignUp(true); setClearSignUp(true);
} }
}} }}
className="text-[#35786f] hover:underline"
> >
{mode === 'signin' {mode === 'signin'
? `${t("noAccount")} ${t("signUp")}` ? `${t("noAccount")} ${t("signUp")}`
: `${t("hasAccount")} ${t("signIn")}` : `${t("hasAccount")} ${t("signIn")}`
} }
</button> </LinkButton>
</div>
</Container>
</div> </div>
</PageLayout>
); );
} }

View File

@@ -1,11 +1,11 @@
import { auth } from "@/auth"; import { auth } from "@/auth";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import AuthForm from "./AuthForm"; import { AuthForm } from "./AuthForm";
export default async function AuthPage( export default async function AuthPage(
props: { props: {
searchParams: Promise<{ [key: string]: string | string[] | undefined; }> searchParams: Promise<{ [key: string]: string | string[] | undefined; }>;
} }
) { ) {
const searchParams = await props.searchParams; const searchParams = await props.searchParams;

View File

@@ -7,28 +7,26 @@ import {
FolderPlus, FolderPlus,
Trash2, Trash2,
} from "lucide-react"; } from "lucide-react";
import { CircleButton, DashedButton } from "@/design-system/base/button";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Center } from "@/components/common/Center";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Folder } from "../../../generated/prisma/browser";
import {
createFolder,
deleteFolderById,
getFoldersWithTotalPairsByUserId,
renameFolderById,
} from "@/lib/server/services/folderService";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { toast } from "sonner"; import { toast } from "sonner";
import { PageLayout } from "@/components/ui/PageLayout";
import { PageHeader } from "@/components/ui/PageHeader";
import { CardList } from "@/components/ui/CardList";
import { actionCreateFolder, actionDeleteFolderById, actionGetFoldersWithTotalPairsByUserId, actionRenameFolderById } from "@/modules/folder/folder-aciton";
import { TSharedFolderWithTotalPairs } from "@/shared/folder-type";
interface FolderProps { interface FolderProps {
folder: Folder & { total: number }; folder: TSharedFolderWithTotalPairs;
refresh: () => void; refresh: () => void;
} }
const FolderCard = ({ folder, refresh }: FolderProps) => { const FolderCard = ({ folder, refresh }: FolderProps) => {
const router = useRouter(); const router = useRouter();
const t = useTranslations("folders"); const t = useTranslations("folders");
return ( return (
<div <div
className="flex justify-between items-center group p-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors" className="flex justify-between items-center group p-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors"
@@ -37,122 +35,145 @@ const FolderCard = ({ folder, refresh }: FolderProps) => {
}} }}
> >
<div className="flex items-center gap-3 flex-1"> <div className="flex items-center gap-3 flex-1">
<div className="w-10 h-10 rounded-lg bg-linear-to-br from-blue-50 to-blue-100 flex items-center justify-center group-hover:from-blue-100 group-hover:to-blue-200 transition-colors"> <div className="shrink-0">
<Fd></Fd> <Fd className="text-gray-600" size="md" />
</div> </div>
<div className="flex-1"> <div className="flex-1">
<h3 className="font-medium text-gray-900"> <h3 className="font-medium text-gray-900">{folder.name}</h3>
<p className="text-sm text-gray-500">
{t("folderInfo", { {t("folderInfo", {
id: folder.id, id: folder.id,
name: folder.name, name: folder.name,
totalPairs: folder.total, totalPairs: folder.total,
})} })}
</h3> </p>
</div>
</div> </div>
<div className="text-xs text-gray-400">#{folder.id}</div> <div className="flex items-center gap-2">
</div> <CircleButton
onClick={(e: React.MouseEvent) => {
<div className="flex items-center gap-2 opacity-50 group-hover:opacity-100 transition-opacity">
<button
onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
const newName = prompt("Input a new name.")?.trim(); const newName = prompt("Input a new name.")?.trim();
if (newName && newName.length > 0) { if (newName && newName.length > 0) {
renameFolderById(folder.id, newName).then(refresh); actionRenameFolderById(folder.id, newName)
.then(result => {
if (result.success) {
refresh();
}
else {
toast.error(result.message);
}
});
} }
}} }}
className="p-2 text-gray-400 hover:bg-red-50 rounded-lg transition-colors"
> >
<FolderPen size={16} /> <FolderPen size={16} />
</button> </CircleButton>
<button <CircleButton
onClick={(e) => { onClick={(e: React.MouseEvent) => {
e.stopPropagation(); e.stopPropagation();
const confirm = prompt(t("confirmDelete", { name: folder.name })); const confirm = prompt(t("confirmDelete", { name: folder.name }));
if (confirm === folder.name) { if (confirm === folder.name) {
deleteFolderById(folder.id).then(refresh); actionDeleteFolderById(folder.id)
.then(result => {
if (result.success) {
refresh();
}
else {
toast.error(result.message);
}
});
} }
}} }}
className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors" className="text-gray-400 hover:text-red-500 hover:bg-red-50"
> >
<Trash2 size={16} /> <Trash2 size={16} />
</button> </CircleButton>
<ChevronRight size={18} className="text-gray-400" /> <ChevronRight size={18} className="text-gray-400" />
</div> </div>
</div> </div>
); );
}; };
export default function FoldersClient({ userId }: { userId: string }) { export function FoldersClient({ userId }: { userId: string; }) {
const t = useTranslations("folders"); const t = useTranslations("folders");
const [folders, setFolders] = useState<(Folder & { total: number })[]>( const [folders, setFolders] = useState<TSharedFolderWithTotalPairs[]>(
[], [],
); );
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
getFoldersWithTotalPairsByUserId(userId) actionGetFoldersWithTotalPairsByUserId(userId)
.then((folders) => { .then((folders) => {
setFolders(folders); if (folders.success && folders.data) {
setFolders(folders.data);
setLoading(false); setLoading(false);
}) }
.catch((error) => {
console.error(error);
toast.error("加载出错,请重试。");
}); });
}, [userId]); }, [userId]);
const updateFolders = async () => { const updateFolders = async () => {
try { setLoading(true);
const updatedFolders = await getFoldersWithTotalPairsByUserId(userId); await actionGetFoldersWithTotalPairsByUserId(userId)
setFolders(updatedFolders); .then(async result => {
} catch (error) { if (!result.success) toast.error(result.message);
console.error(error); else await actionGetFoldersWithTotalPairsByUserId(userId)
.then((folders) => {
if (folders.success && folders.data) {
setFolders(folders.data);
} }
});
});
setLoading(false);
}; };
return (
<Center>
<div className="w-full max-w-2xl mx-auto bg-white border border-gray-200 rounded-2xl p-6">
<div className="mb-6">
<h1 className="text-2xl font-light text-gray-900">{t("title")}</h1>
<p className="text-sm text-gray-500 mt-1">{t("subtitle")}</p>
</div>
<button return (
<PageLayout>
<PageHeader title={t("title")} subtitle={t("subtitle")} />
{/* 新建文件夹按钮 */}
<DashedButton
onClick={async () => { onClick={async () => {
const folderName = prompt(t("enterFolderName")); const folderName = prompt(t("enterFolderName"));
if (!folderName) return; if (!folderName) return;
setLoading(true); setLoading(true);
try { try {
await createFolder({ await actionCreateFolder(userId, folderName)
name: folderName, .then(result => {
user: { connect: { id: userId } }, if (result.success) {
updateFolders();
} else {
toast.error(result.message);
}
}); });
await updateFolders();
} finally { } finally {
setLoading(false); setLoading(false);
} }
}} }}
disabled={loading} disabled={loading}
className="w-full p-3 border-2 border-dashed border-gray-300 rounded-xl text-gray-500 hover:border-gray-400 hover:text-gray-600 transition-colors flex items-center justify-center gap-2" className="w-full"
> >
<FolderPlus size={18} /> <FolderPlus size={18} />
<span>{loading ? t("creating") : t("newFolder")}</span> <span>{loading ? t("creating") : t("newFolder")}</span>
</button> </DashedButton>
<div className="mt-4 max-h-96 overflow-y-auto"> {/* 文件夹列表 */}
<div className="mt-4">
<CardList>
{folders.length === 0 ? ( {folders.length === 0 ? (
// 空状态
<div className="text-center py-12 text-gray-400"> <div className="text-center py-12 text-gray-400">
<div className="w-16 h-16 mx-auto mb-3 rounded-lg bg-gray-100 flex items-center justify-center"> <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-gray-100 flex items-center justify-center">
<FolderPlus size={24} className="text-gray-400" /> <FolderPlus size="md" className="text-gray-400" />
</div> </div>
<p className="text-sm">{t("noFoldersYet")}</p> <p className="text-sm">{t("noFoldersYet")}</p>
</div> </div>
) : ( ) : (
<div className="rounded-xl border border-gray-200 overflow-hidden"> // 文件夹卡片列表
<div className="rounded-md border border-gray-200 overflow-hidden">
{folders {folders
.toSorted((a, b) => a.id - b.id) .toSorted((a, b) => a.id - b.id)
.map((folder) => ( .map((folder) => (
@@ -164,8 +185,8 @@ export default function FoldersClient({ userId }: { userId: string }) {
))} ))}
</div> </div>
)} )}
</CardList>
</div> </div>
</div> </PageLayout>
</Center>
); );
} }

View File

@@ -1,7 +1,8 @@
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import Input from "@/components/ui/Input"; import { Input } from "@/design-system/base/input";
import { LocaleSelector } from "@/components/ui/LocaleSelector";
import { X } from "lucide-react"; import { X } from "lucide-react";
import { useRef } from "react"; import { useRef, useState } from "react";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
interface AddTextPairModalProps { interface AddTextPairModalProps {
@@ -10,12 +11,12 @@ interface AddTextPairModalProps {
onAdd: ( onAdd: (
text1: string, text1: string,
text2: string, text2: string,
locale1: string, language1: string,
locale2: string, language2: string,
) => void; ) => void;
} }
export default function AddTextPairModal({ export function AddTextPairModal({
isOpen, isOpen,
onClose, onClose,
onAdd, onAdd,
@@ -23,38 +24,39 @@ export default function AddTextPairModal({
const t = useTranslations("folder_id"); const t = useTranslations("folder_id");
const input1Ref = useRef<HTMLInputElement>(null); const input1Ref = useRef<HTMLInputElement>(null);
const input2Ref = useRef<HTMLInputElement>(null); const input2Ref = useRef<HTMLInputElement>(null);
const input3Ref = useRef<HTMLInputElement>(null); const [language1, setLanguage1] = useState("english");
const input4Ref = useRef<HTMLInputElement>(null); const [language2, setLanguage2] = useState("chinese");
if (!isOpen) return null; if (!isOpen) return null;
const handleAdd = () => { const handleAdd = () => {
if ( if (
!input1Ref.current?.value || !input1Ref.current?.value ||
!input2Ref.current?.value || !input2Ref.current?.value ||
!input3Ref.current?.value || !language1 ||
!input4Ref.current?.value !language2
) )
return; return;
const text1 = input1Ref.current.value; const text1 = input1Ref.current.value;
const text2 = input2Ref.current.value; const text2 = input2Ref.current.value;
const locale1 = input3Ref.current.value;
const locale2 = input4Ref.current.value;
if ( if (
typeof text1 === "string" && typeof text1 === "string" &&
typeof text2 === "string" && typeof text2 === "string" &&
typeof locale1 === "string" && typeof language1 === "string" &&
typeof locale2 === "string" && typeof language2 === "string" &&
text1.trim() !== "" && text1.trim() !== "" &&
text2.trim() !== "" && text2.trim() !== "" &&
locale1.trim() !== "" && language1.trim() !== "" &&
locale2.trim() !== "" language2.trim() !== ""
) { ) {
onAdd(text1, text2, locale1, locale2); onAdd(text1, text2, language1, language2);
input1Ref.current.value = ""; input1Ref.current.value = "";
input2Ref.current.value = ""; input2Ref.current.value = "";
} }
}; };
return ( return (
<div <div
className="fixed inset-0 bg-black/50 backdrop-blur flex items-center justify-center z-50" className="fixed inset-0 bg-black/50 backdrop-blur flex items-center justify-center z-50"
@@ -65,7 +67,7 @@ export default function AddTextPairModal({
} }
}} }}
> >
<div className="bg-white rounded-xl p-6 w-full max-w-md mx-4"> <div className="bg-white rounded-md p-6 w-full max-w-md mx-4">
<div className="flex"> <div className="flex">
<h2 className="flex-1 text-xl font-light mb-4 text-center"> <h2 className="flex-1 text-xl font-light mb-4 text-center">
{t("addNewTextPair")} {t("addNewTextPair")}
@@ -82,20 +84,12 @@ export default function AddTextPairModal({
<Input ref={input2Ref} className="w-full"></Input> <Input ref={input2Ref} className="w-full"></Input>
</div> </div>
<div> <div>
{t("locale1")} {t("language1")}
<Input <LocaleSelector value={language1} onChange={setLanguage1} />
ref={input3Ref}
className="w-full"
placeholder="en-US"
></Input>
</div> </div>
<div> <div>
{t("locale2")} {t("language2")}
<Input <LocaleSelector value={language2} onChange={setLanguage2} />
ref={input4Ref}
className="w-full"
placeholder="zh-CN"
></Input>
</div> </div>
</div> </div>
<LightButton onClick={handleAdd}>{t("add")}</LightButton> <LightButton onClick={handleAdd}>{t("add")}</LightButton>

View File

@@ -1,30 +1,21 @@
"use client"; "use client";
import { ArrowLeft, Plus } from "lucide-react"; import { ArrowLeft, Plus } from "lucide-react";
import { Center } from "@/components/common/Center";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { redirect, useRouter } from "next/navigation"; import { redirect, useRouter } from "next/navigation";
import Container from "@/components/ui/Container"; import { AddTextPairModal } from "./AddTextPairModal";
import { import { TextPairCard } from "./TextPairCard";
createPair,
deletePairById,
getPairsByFolderId,
} from "@/lib/server/services/pairService";
import AddTextPairModal from "./AddTextPairModal";
import TextPairCard from "./TextPairCard";
import LightButton from "@/components/ui/buttons/LightButton";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { PageLayout } from "@/components/ui/PageLayout";
import { PrimaryButton, IconButton, LinkButton } from "@/design-system/base/button";
import { CardList } from "@/components/ui/CardList";
import { actionCreatePair, actionDeletePairById, actionGetPairsByFolderId } from "@/modules/folder/folder-aciton";
import { TSharedPair } from "@/shared/folder-type";
import { toast } from "sonner";
export interface TextPair {
id: number;
text1: string;
text2: string;
locale1: string;
locale2: string;
}
export default function InFolder({ folderId }: { folderId: number }) { export function InFolder({ folderId, isReadOnly }: { folderId: number; isReadOnly: boolean; }) {
const [textPairs, setTextPairs] = useState<TextPair[]>([]); const [textPairs, setTextPairs] = useState<TSharedPair[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [openAddModal, setAddModal] = useState(false); const [openAddModal, setAddModal] = useState(false);
const router = useRouter(); const router = useRouter();
@@ -33,83 +24,89 @@ export default function InFolder({ folderId }: { folderId: number }) {
useEffect(() => { useEffect(() => {
const fetchTextPairs = async () => { const fetchTextPairs = async () => {
setLoading(true); setLoading(true);
try { await actionGetPairsByFolderId(folderId)
const data = await getPairsByFolderId(folderId); .then(result => {
setTextPairs(data as TextPair[]); if (!result.success || !result.data) throw result.message;
} catch (error) { return result.data;
console.error("Failed to fetch text pairs:", error); }).then(setTextPairs)
} finally { .catch(toast.error)
.finally(() => {
setLoading(false); setLoading(false);
} });
}; };
fetchTextPairs(); fetchTextPairs();
}, [folderId]); }, [folderId]);
const refreshTextPairs = async () => { const refreshTextPairs = async () => {
try { await actionGetPairsByFolderId(folderId)
const data = await getPairsByFolderId(folderId); .then(result => {
setTextPairs(data as TextPair[]); if (!result.success || !result.data) throw result.message;
} catch (error) { return result.data;
console.error("Failed to fetch text pairs:", error); }).then(setTextPairs)
} .catch(toast.error);
}; };
return ( return (
<Center> <PageLayout>
<Container className="p-6"> {/* 顶部导航和标题栏 */}
<div className="mb-6"> <div className="mb-6">
<button {/* 返回按钮 */}
<LinkButton
onClick={router.back} onClick={router.back}
className="flex items-center gap-2 text-gray-500 hover:text-gray-700 transition-colors mb-4" className="flex items-center gap-2 mb-4"
> >
<ArrowLeft size={16} /> <ArrowLeft size={16} />
<span className="text-sm">{t("back")}</span> <span className="text-sm">{t("back")}</span>
</button> </LinkButton>
{/* 页面标题和操作按钮 */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
{/* 标题区域 */}
<div> <div>
<h1 className="text-2xl font-light text-gray-900"> <h1 className="text-2xl md:text-3xl font-bold text-gray-800 mb-1">
{t("textPairs")} {t("textPairs")}
</h1> </h1>
<p className="text-sm text-gray-500 mt-1"> <p className="text-sm text-gray-500">
{t("itemsCount", { count: textPairs.length })} {t("itemsCount", { count: textPairs.length })}
</p> </p>
</div> </div>
{/* 操作按钮区域 */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<LightButton <PrimaryButton
onClick={() => { onClick={() => {
redirect(`/memorize?folder_id=${folderId}`); redirect(`/memorize?folder_id=${folderId}`);
}} }}
> >
{t("memorize")} {t("memorize")}
</LightButton> </PrimaryButton>
<button {!isReadOnly && (
className="p-2 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors" <IconButton
onClick={() => { onClick={() => {
setAddModal(true); setAddModal(true);
}} }}
> icon={<Plus size={18} className="text-gray-700" />}
<Plus
size={18}
className="text-gray-600 hover:cursor-pointer"
/> />
</button> )}
</div> </div>
</div> </div>
</div> </div>
<div className="max-h-96 overflow-y-auto rounded-xl border border-gray-200 overflow-hidden"> {/* 文本对列表 */}
<CardList>
{loading ? ( {loading ? (
// 加载状态
<div className="p-8 text-center"> <div className="p-8 text-center">
<div className="w-8 h-8 border-2 border-gray-200 border-t-gray-400 rounded-full animate-spin mx-auto mb-3"></div> <div className="w-8 h-8 border-2 border-gray-200 border-t-gray-400 rounded-full animate-spin mx-auto mb-3"></div>
<p className="text-sm text-gray-500">{t("loadingTextPairs")}</p> <p className="text-sm text-gray-500">{t("loadingTextPairs")}</p>
</div> </div>
) : textPairs.length === 0 ? ( ) : textPairs.length === 0 ? (
// 空状态
<div className="p-12 text-center"> <div className="p-12 text-center">
<p className="text-sm text-gray-500 mb-2">{t("noTextPairs")}</p> <p className="text-sm text-gray-500 mb-2">{t("noTextPairs")}</p>
</div> </div>
) : ( ) : (
// 文本对卡片列表
<div className="divide-y divide-gray-100"> <div className="divide-y divide-gray-100">
{textPairs {textPairs
.toSorted((a, b) => a.id - b.id) .toSorted((a, b) => a.id - b.id)
@@ -117,40 +114,41 @@ export default function InFolder({ folderId }: { folderId: number }) {
<TextPairCard <TextPairCard
key={textPair.id} key={textPair.id}
textPair={textPair} textPair={textPair}
isReadOnly={isReadOnly}
onDel={() => { onDel={() => {
deletePairById(textPair.id); actionDeletePairById(textPair.id)
refreshTextPairs(); .then(result => {
if (!result.success) throw result.message;
}).then(refreshTextPairs)
.catch(toast.error);
}} }}
refreshTextPairs={refreshTextPairs} refreshTextPairs={refreshTextPairs}
/> />
))} ))}
</div> </div>
)} )}
</div> </CardList>
</Container>
{/* 添加文本对模态框 */}
<AddTextPairModal <AddTextPairModal
isOpen={openAddModal} isOpen={openAddModal}
onClose={() => setAddModal(false)} onClose={() => setAddModal(false)}
onAdd={async ( onAdd={async (
text1: string, text1: string,
text2: string, text2: string,
locale1: string, language1: string,
locale2: string, language2: string,
) => { ) => {
await createPair({ await actionCreatePair({
text1: text1, text1: text1,
text2: text2, text2: text2,
locale1: locale1, language1: language1,
locale2: locale2, language2: language2,
folder: { folderId: folderId,
connect: {
id: folderId,
},
},
}); });
refreshTextPairs(); refreshTextPairs();
}} }}
/> />
</Center> </PageLayout>
); );
} };

View File

@@ -1,19 +1,23 @@
import { Edit, Trash2 } from "lucide-react"; import { Edit, Trash2 } from "lucide-react";
import { TextPair } from "./InFolder";
import { updatePairById } from "@/lib/server/services/pairService";
import { useState } from "react"; import { useState } from "react";
import UpdateTextPairModal from "./UpdateTextPairModal"; import { CircleButton } from "@/design-system/base/button";
import { UpdateTextPairModal } from "./UpdateTextPairModal";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { PairUpdateInput } from "../../../../generated/prisma/models"; import { TSharedPair } from "@/shared/folder-type";
import { actionUpdatePairById } from "@/modules/folder/folder-aciton";
import { ActionInputUpdatePairById } from "@/modules/folder/folder-action-dto";
import { toast } from "sonner";
interface TextPairCardProps { interface TextPairCardProps {
textPair: TextPair; textPair: TSharedPair;
isReadOnly: boolean;
onDel: () => void; onDel: () => void;
refreshTextPairs: () => void; refreshTextPairs: () => void;
} }
export default function TextPairCard({ export function TextPairCard({
textPair, textPair,
isReadOnly,
onDel, onDel,
refreshTextPairs, refreshTextPairs,
}: TextPairCardProps) { }: TextPairCardProps) {
@@ -25,29 +29,33 @@ export default function TextPairCard({
<div className="flex items-start justify-between mb-3"> <div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2 text-xs text-gray-500"> <div className="flex items-center gap-2 text-xs text-gray-500">
<span className="px-2 py-1 bg-gray-100 rounded-md"> <span className="px-2 py-1 bg-gray-100 rounded-md">
{textPair.locale1.toUpperCase()} {textPair.language1.toUpperCase()}
</span> </span>
<span></span> <span></span>
<span className="px-2 py-1 bg-gray-100 rounded-md"> <span className="px-2 py-1 bg-gray-100 rounded-md">
{textPair.locale2.toUpperCase()} {textPair.language2.toUpperCase()}
</span> </span>
</div> </div>
<div className="flex items-center gap-1 opacity-50 group-hover:opacity-100 transition-opacity"> <div className="flex items-center gap-1 opacity-50 group-hover:opacity-100 transition-opacity">
<button {!isReadOnly && (
className="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-md transition-colors" <>
<CircleButton
onClick={() => setOpenUpdateModal(true)} onClick={() => setOpenUpdateModal(true)}
title={t("edit")} title={t("edit")}
className="text-gray-400 hover:text-gray-600"
> >
<Edit size={14} /> <Edit size={14} />
</button> </CircleButton>
<button <CircleButton
className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-md transition-colors"
onClick={onDel} onClick={onDel}
title={t("delete")} title={t("delete")}
className="text-gray-400 hover:text-red-500 hover:bg-red-50"
> >
<Trash2 size={14} /> <Trash2 size={14} />
</button> </CircleButton>
</>
)}
</div> </div>
</div> </div>
<div className="text-gray-900 grid grid-cols-2 gap-4 w-3/4"> <div className="text-gray-900 grid grid-cols-2 gap-4 w-3/4">
@@ -66,8 +74,8 @@ export default function TextPairCard({
<UpdateTextPairModal <UpdateTextPairModal
isOpen={openUpdateModal} isOpen={openUpdateModal}
onClose={() => setOpenUpdateModal(false)} onClose={() => setOpenUpdateModal(false)}
onUpdate={async (id: number, data: PairUpdateInput) => { onUpdate={async (id: number, data: ActionInputUpdatePairById) => {
await updatePairById(id, data); await actionUpdatePairById(id, data).then(result => result.success ? toast.success(result.message) : toast.error(result.message));
setOpenUpdateModal(false); setOpenUpdateModal(false);
refreshTextPairs(); refreshTextPairs();
}} }}

View File

@@ -1,19 +1,20 @@
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import Input from "@/components/ui/Input"; import { Input } from "@/design-system/base/input";
import { LocaleSelector } from "@/components/ui/LocaleSelector";
import { X } from "lucide-react"; import { X } from "lucide-react";
import { useRef } from "react"; import { useRef, useState } from "react";
import { PairUpdateInput } from "../../../../generated/prisma/models";
import { TextPair } from "./InFolder";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { TSharedPair } from "@/shared/folder-type";
import { ActionInputUpdatePairById } from "@/modules/folder/folder-action-dto";
interface UpdateTextPairModalProps { interface UpdateTextPairModalProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
textPair: TextPair; textPair: TSharedPair;
onUpdate: (id: number, tp: PairUpdateInput) => void; onUpdate: (id: number, tp: ActionInputUpdatePairById) => void;
} }
export default function UpdateTextPairModal({ export function UpdateTextPairModal({
isOpen, isOpen,
onClose, onClose,
onUpdate, onUpdate,
@@ -22,36 +23,34 @@ export default function UpdateTextPairModal({
const t = useTranslations("folder_id"); const t = useTranslations("folder_id");
const input1Ref = useRef<HTMLInputElement>(null); const input1Ref = useRef<HTMLInputElement>(null);
const input2Ref = useRef<HTMLInputElement>(null); const input2Ref = useRef<HTMLInputElement>(null);
const input3Ref = useRef<HTMLInputElement>(null); const [language1, setLanguage1] = useState(textPair.language1);
const input4Ref = useRef<HTMLInputElement>(null); const [language2, setLanguage2] = useState(textPair.language2);
if (!isOpen) return null; if (!isOpen) return null;
const handleUpdate = () => { const handleUpdate = () => {
if ( if (
!input1Ref.current?.value || !input1Ref.current?.value ||
!input2Ref.current?.value || !input2Ref.current?.value ||
!input3Ref.current?.value || !language1 ||
!input4Ref.current?.value !language2
) )
return; return;
const text1 = input1Ref.current.value; const text1 = input1Ref.current.value;
const text2 = input2Ref.current.value; const text2 = input2Ref.current.value;
const locale1 = input3Ref.current.value;
const locale2 = input4Ref.current.value;
if ( if (
typeof text1 === "string" && typeof text1 === "string" &&
typeof text2 === "string" && typeof text2 === "string" &&
typeof locale1 === "string" && typeof language1 === "string" &&
typeof locale2 === "string" && typeof language2 === "string" &&
text1.trim() !== "" && text1.trim() !== "" &&
text2.trim() !== "" && text2.trim() !== "" &&
locale1.trim() !== "" && language1.trim() !== "" &&
locale2.trim() !== "" language2.trim() !== ""
) { ) {
onUpdate(textPair.id, { text1, text2, locale1, locale2 }); onUpdate(textPair.id, { text1, text2, language1, language2 });
input1Ref.current.value = "";
input2Ref.current.value = "";
} }
}; };
return ( return (
@@ -64,7 +63,7 @@ export default function UpdateTextPairModal({
} }
}} }}
> >
<div className="bg-white rounded-xl p-6 w-full max-w-md mx-4"> <div className="bg-white rounded-md p-6 w-full max-w-md mx-4">
<div className="flex"> <div className="flex">
<h2 className="flex-1 text-xl font-light mb-4 text-center"> <h2 className="flex-1 text-xl font-light mb-4 text-center">
{t("updateTextPair")} {t("updateTextPair")}
@@ -89,20 +88,12 @@ export default function UpdateTextPairModal({
></Input> ></Input>
</div> </div>
<div> <div>
{t("locale1")} {t("language1")}
<Input <LocaleSelector value={language1} onChange={setLanguage1} />
defaultValue={textPair.locale1}
ref={input3Ref}
className="w-full"
></Input>
</div> </div>
<div> <div>
{t("locale2")} {t("language2")}
<Input <LocaleSelector value={language2} onChange={setLanguage2} />
defaultValue={textPair.locale2}
ref={input4Ref}
className="w-full"
></Input>
</div> </div>
</div> </div>
<LightButton onClick={handleUpdate}>{t("update")}</LightButton> <LightButton onClick={handleUpdate}>{t("update")}</LightButton>

View File

@@ -1,9 +1,10 @@
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server"; import { getTranslations } from "next-intl/server";
import InFolder from "./InFolder"; import { InFolder } from "./InFolder";
import { getUserIdByFolderId } from "@/lib/server/services/folderService";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { actionGetUserIdByFolderId } from "@/modules/folder/folder-aciton";
export default async function FoldersPage({ export default async function FoldersPage({
params, params,
}: { }: {
@@ -16,9 +17,11 @@ export default async function FoldersPage({
if (!folder_id) { if (!folder_id) {
redirect("/folders"); redirect("/folders");
} }
if (!session) redirect(`/auth?redirect=/folders/${folder_id}`);
if ((await getUserIdByFolderId(Number(folder_id))) !== session.user.id) { // Allow non-authenticated users to view folders (read-only mode)
return <p>{t("unauthorized")}</p>; const folderUserId = (await actionGetUserIdByFolderId(Number(folder_id))).data;
} const isOwner = session?.user?.id === folderUserId;
return <InFolder folderId={Number(folder_id)} />; const isReadOnly = !isOwner;
return <InFolder folderId={Number(folder_id)} isReadOnly={isReadOnly} />;
} }

View File

@@ -1,5 +1,5 @@
import { auth } from "@/auth"; import { auth } from "@/auth";
import FoldersClient from "./FoldersClient"; import { FoldersClient } from "./FoldersClient";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { headers } from "next/headers"; import { headers } from "next/headers";

View File

@@ -1,30 +1,230 @@
@import "tailwindcss"; @import "tailwindcss";
/**
* Tailwind CSS v4 主题配置
* 使用 @theme 指令定义主题变量
*/
@theme {
/* 主色 - Teal */
--color-primary-50: #f0f9f8;
--color-primary-100: #e0f2f0;
--color-primary-200: #bce6e1;
--color-primary-300: #8dd4cc;
--color-primary-400: #5ec2b7;
--color-primary-500: #35786f;
--color-primary-600: #2a605b;
--color-primary-700: #1f4844;
--color-primary-800: #183835;
--color-primary-900: #122826;
--color-primary-950: #0a1413;
/* 中性色 */
--color-gray-50: #f9fafb;
--color-gray-100: #f3f4f6;
--color-gray-200: #e5e7eb;
--color-gray-300: #d1d5db;
--color-gray-400: #9ca3af;
--color-gray-500: #6b7280;
--color-gray-600: #4b5563;
--color-gray-700: #374151;
--color-gray-800: #1f2937;
--color-gray-900: #111827;
--color-gray-950: #030712;
/* 语义色 - Success */
--color-success-50: #f0fdf4;
--color-success-100: #dcfce7;
--color-success-200: #bbf7d0;
--color-success-300: #86efac;
--color-success-400: #4ade80;
--color-success-500: #22c55e;
--color-success-600: #16a34a;
--color-success-700: #15803d;
--color-success-800: #166534;
--color-success-900: #14532d;
--color-success-950: #052e16;
/* 语义色 - Warning */
--color-warning-50: #fffbeb;
--color-warning-100: #fef3c7;
--color-warning-200: #fde68a;
--color-warning-300: #fcd34d;
--color-warning-400: #fbbf24;
--color-warning-500: #f59e0b;
--color-warning-600: #d97706;
--color-warning-700: #b45309;
--color-warning-800: #92400e;
--color-warning-900: #78350f;
--color-warning-950: #451a03;
/* 语义色 - Error */
--color-error-50: #fef2f2;
--color-error-100: #fee2e2;
--color-error-200: #fecaca;
--color-error-300: #fca5a5;
--color-error-400: #f87171;
--color-error-500: #ef4444;
--color-error-600: #dc2626;
--color-error-700: #b91c1c;
--color-error-800: #991b1b;
--color-error-900: #7f1d1d;
--color-error-950: #450a0a;
/* 语义色 - Info */
--color-info-50: #eff6ff;
--color-info-100: #dbeafe;
--color-info-200: #bfdbfe;
--color-info-300: #93c5fd;
--color-info-400: #60a5fa;
--color-info-500: #3b82f6;
--color-info-600: #2563eb;
--color-info-700: #1d4ed8;
--color-info-800: #1e40af;
--color-info-900: #1e3a8a;
--color-info-950: #172554;
/* 圆角 - 更小的圆角 */
--radius-xs: 0.125rem;
--radius-sm: 0.25rem;
--radius-md: 0.375rem;
--radius-lg: 0.5rem;
--radius-xl: 0.625rem;
--radius-2xl: 0.75rem;
--radius-3xl: 1rem;
--radius-full: 9999px;
}
/**
* Design System CSS 变量
*
* 定义全局 CSS 变量用于主题切换和动态样式
*/
:root { :root {
/* 基础颜色 */
--background: #ffffff; --background: #ffffff;
--foreground: #171717; --foreground: #111827;
--foreground-secondary: #4b5563;
--foreground-tertiary: #6b7280;
--foreground-disabled: #9ca3af;
/* 背景 */
--background-secondary: #f3f4f6;
--background-tertiary: #e5e7eb;
/* 边框 */
--border: #d1d5db;
--border-secondary: #e5e7eb;
--border-focus: #35786f;
/* 圆角 - 更小的圆角 */
--radius-xs: 0.125rem;
--radius-sm: 0.25rem;
--radius-md: 0.375rem;
--radius-lg: 0.5rem;
--radius-xl: 0.625rem;
--radius-2xl: 0.75rem;
--radius-3xl: 1rem;
--radius-full: 9999px;
/* 阴影 */
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
--shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
--shadow-2xl: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
--shadow-primary: 0 4px 14px 0 rgba(53, 120, 111, 0.39);
/* 间距 */
--spacing-xs: 0.25rem;
--spacing-sm: 0.5rem;
--spacing-md: 1rem;
--spacing-lg: 1.5rem;
--spacing-xl: 2rem;
--spacing-2xl: 3rem;
/* 过渡 */
--transition-fast: 150ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-base: 250ms cubic-bezier(0.4, 0, 0.2, 1);
--transition-slow: 350ms cubic-bezier(0.4, 0, 0.2, 1);
} }
@theme inline { /**
--color-background: var(--background); * 全局基础样式
--color-foreground: var(--foreground); */
--font-sans: var(--font-geist-sans); * {
--font-mono: var(--font-geist-mono); box-sizing: border-box;
} }
/* @media (prefers-color-scheme: dark) { html {
:root { height: 100%;
--background: #0a0a0a; -webkit-font-smoothing: antialiased;
--foreground: #ededed; -moz-osx-font-smoothing: grayscale;
} }
} */
body { body {
height: 100%;
margin: 0;
padding: 0;
background: var(--background); background: var(--background);
color: var(--foreground); color: var(--foreground);
font-family: var(--font-geist-sans), Arial, Helvetica, sans-serif; font-family: var(--font-geist-sans), -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
font-size: 1rem;
line-height: 1.5;
text-rendering: optimizeLegibility;
} }
.code-block { /**
font-family: var(--font-geist-mono), monospace; * 代码块字体
*/
.code-block,
code,
kbd,
pre,
samp {
font-family: var(--font-geist-mono), ui-monospace, SFMono-Regular, Monaco, Consolas, monospace;
}
/**
* 导航栏按钮样式
*/
.navbar-btn {
@apply border-0 bg-transparent hover:bg-black/30 shadow-none;
transition: background-color var(--transition-fast);
}
/**
* 焦点可见性优化
*/
:focus-visible {
outline: 2px solid var(--border-focus);
outline-offset: 2px;
}
/**
* 选择文本样式
*/
::selection {
background-color: var(--color-primary-200);
color: var(--color-primary-900);
}
/**
* 滚动条样式
*/
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--background-secondary);
}
::-webkit-scrollbar-thumb {
background: var(--foreground-tertiary);
border-radius: var(--radius-full);
}
::-webkit-scrollbar-thumb:hover {
background: var(--foreground-secondary);
} }

View File

@@ -13,7 +13,7 @@ function LinkArea({ href, name, description, color }: LinkAreaProps) {
<Link <Link
href={href} href={href}
style={{ backgroundColor: color }} style={{ backgroundColor: color }}
className={`h-32 md:h-64 flex md:justify-center items-center`} className={`hover:scale-105 transition-transform duration-200 h-32 md:h-64 flex md:justify-center items-center`}
> >
<div className="text-white m-8"> <div className="text-white m-8">
<h1 className="md:text-4xl text-3xl">{name}</h1> <h1 className="md:text-4xl text-3xl">{name}</h1>
@@ -60,6 +60,12 @@ export default async function HomePage() {
description={t("srtPlayer.description")} description={t("srtPlayer.description")}
color="#3c988d" color="#3c988d"
></LinkArea> ></LinkArea>
<LinkArea
href="/dictionary"
name={t("dictionary.name")}
description={t("dictionary.description")}
color="#6a9c89"
></LinkArea>
<LinkArea <LinkArea
href="/alphabet" href="/alphabet"
name={t("alphabet.name")} name={t("alphabet.name")}

View File

@@ -1,40 +1,16 @@
import Image from "next/image";
import { Center } from "@/components/common/Center";
import Container from "@/components/ui/Container";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { getTranslations } from "next-intl/server";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { headers } from "next/headers"; import { headers } from "next/headers";
import LogoutButton from "./LogoutButton";
export default async function ProfilePage() { export default async function ProfilePage() {
const t = await getTranslations("profile");
const session = await auth.api.getSession({ headers: await headers() }); const session = await auth.api.getSession({ headers: await headers() });
if (!session) { if (!session) {
redirect("/auth?redirect=/profile"); redirect("/auth?redirect=/profile");
} }
console.log(JSON.stringify(session, null, 2)); // 已登录,跳转到用户资料页面
// 优先使用 username如果没有则使用 email
return ( const username = (session.user.username as string) || (session.user.email as string);
<Center> redirect(`/users/${username}`);
<Container className="p-6">
<h1>{t("myProfile")}</h1>
{session.user.image && (
<Image
width={64}
height={64}
alt="User Avatar"
src={session.user.image as string}
className="rounded-4xl"
></Image>
)}
<p>{session.user.name}</p>
<p>{t("email", { email: session.user.email })}</p>
<LogoutButton />
</Container>
</Center>
);
} }

View File

@@ -1,11 +1,11 @@
"use client"; "use client";
import LightButton from "@/components/ui/buttons/LightButton"; import { LightButton } from "@/design-system/base/button";
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
export default function LogoutButton() { export function LogoutButton() {
const t = useTranslations("profile"); const t = useTranslations("profile");
const router = useRouter(); const router = useRouter();
return <LightButton onClick={async () => { return <LightButton onClick={async () => {

View File

@@ -0,0 +1,195 @@
import Image from "next/image";
import Link from "next/link";
import { PageLayout } from "@/components/ui/PageLayout";
import { LinkButton } from "@/design-system/base/button";
import { actionGetUserProfileByUsername } from "@/modules/auth/auth-action";
import { repoGetFoldersWithTotalPairsByUserId } from "@/modules/folder/folder-repository";
import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { auth } from "@/auth";
import { headers } from "next/headers";
import { LogoutButton } from "@/app/users/[username]/LogoutButton";
interface UserPageProps {
params: Promise<{ username: string; }>;
}
export default async function UserPage({ params }: UserPageProps) {
const { username } = await params;
const t = await getTranslations("user_profile");
// Get current session
const session = await auth.api.getSession({ headers: await headers() });
// Get user profile
const result = await actionGetUserProfileByUsername({ username });
if (!result.success || !result.data) {
notFound();
}
const user = result.data;
// Get user's folders
const folders = await repoGetFoldersWithTotalPairsByUserId(user.id);
// Check if viewing own profile
const isOwnProfile = session?.user?.username === username || session?.user?.email === username;
return (
<PageLayout>
{/* Header */}
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<div className="flex items-center justify-between mb-4">
<div></div>
{isOwnProfile && <LogoutButton />}
</div>
<div className="flex items-center space-x-6">
{/* Avatar */}
{user.image ? (
<div className="relative w-24 h-24 rounded-full border-4 border-[#35786f] overflow-hidden">
<Image
src={user.image}
alt={user.displayUsername || user.username || user.email}
fill
className="object-cover"
unoptimized
/>
</div>
) : (
<div className="w-24 h-24 rounded-full bg-[#35786f] border-4 border-[#35786f] flex items-center justify-center">
<span className="text-3xl font-bold text-white">
{(user.displayUsername || user.username || user.email)[0].toUpperCase()}
</span>
</div>
)}
{/* User Info */}
<div className="flex-1">
<h1 className="text-3xl font-bold text-gray-800 mb-2">
{user.displayUsername || user.username || t("anonymous")}
</h1>
{user.username && (
<p className="text-gray-600 text-sm mb-1">
@{user.username}
</p>
)}
<div className="flex items-center space-x-4 text-sm">
<span className="text-gray-500">
Joined: {new Date(user.createdAt).toLocaleDateString()}
</span>
{user.emailVerified && (
<span className="flex items-center text-green-600">
<svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 00016zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.293 12.293a1 1 0 101.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
</svg>
Verified
</span>
)}
</div>
</div>
</div>
</div>
{/* Email Section */}
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<h2 className="text-xl font-semibold text-gray-800 mb-4">{t("email")}</h2>
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<span className="text-gray-700">{user.email}</span>
</div>
{user.emailVerified ? (
<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
{t("verified")}
</span>
) : (
<span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-100 text-yellow-800">
{t("unverified")}
</span>
)}
</div>
</div>
{/* Account Info */}
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<h2 className="text-xl font-semibold text-gray-800 mb-4">{t("accountInfo")}</h2>
<dl className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<dt className="text-sm font-medium text-gray-500">{t("userId")}</dt>
<dd className="mt-1 text-sm text-gray-900 font-mono break-all">{user.id}</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">{t("username")}</dt>
<dd className="mt-1 text-sm text-gray-900">
{user.username || <span className="text-gray-400">{t("notSet")}</span>}
</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">{t("displayName")}</dt>
<dd className="mt-1 text-sm text-gray-900">
{user.displayUsername || <span className="text-gray-400">{t("notSet")}</span>}
</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">{t("memberSince")}</dt>
<dd className="mt-1 text-sm text-gray-900">
{new Date(user.createdAt).toLocaleDateString()}
</dd>
</div>
</dl>
</div>
{/* Folders Section */}
<div className="bg-white rounded-lg shadow-md p-6">
<h2 className="text-xl font-semibold text-gray-800 mb-4">{t("folders.title")}</h2>
{folders.length === 0 ? (
<p className="text-gray-500 text-center py-8">{t("folders.noFolders")}</p>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t("folders.folderName")}
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t("folders.totalPairs")}
</th>
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t("folders.createdAt")}
</th>
<th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
{t("folders.actions")}
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{folders.map((folder) => (
<tr key={folder.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm font-medium text-gray-900">{folder.name}</div>
<div className="text-sm text-gray-500">ID: {folder.id}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900">{folder.total}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{new Date(folder.createdAt).toLocaleDateString()}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<Link href={`/folders/${folder.id}`}>
<LinkButton>
{t("folders.view")}
</LinkButton>
</Link>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</PageLayout>
);
}

View File

@@ -1,7 +1,8 @@
import { betterAuth } from "better-auth"; import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma"; import { prismaAdapter } from "better-auth/adapters/prisma";
import { nextCookies } from "better-auth/next-js"; import { nextCookies } from "better-auth/next-js";
import prisma from "./lib/db"; import { prisma } from "./lib/db";
import { username } from "better-auth/plugins";
export const auth = betterAuth({ export const auth = betterAuth({
database: prismaAdapter(prisma, { database: prismaAdapter(prisma, {
@@ -16,5 +17,5 @@ export const auth = betterAuth({
clientSecret: process.env.GITHUB_CLIENT_SECRET as string clientSecret: process.env.GITHUB_CLIENT_SECRET as string
}, },
}, },
plugins: [nextCookies()] plugins: [nextCookies(), username()]
}); });

View File

@@ -1,46 +0,0 @@
"use client";
import IMAGES from "@/config/images";
import IconClick from "./ui/buttons/IconClick";
import { useState } from "react";
import GhostButton from "./ui/buttons/GhostButton";
export default function LanguageSettings() {
const [showLanguageMenu, setShowLanguageMenu] = useState(false);
const handleLanguageClick = () => {
setShowLanguageMenu((prev) => !prev);
};
const setLocale = async (locale: string) => {
document.cookie = `locale=${locale}`;
window.location.reload();
};
return (
<>
<IconClick
src={IMAGES.language_white}
alt="language"
disableOnHoverBgChange={true}
onClick={handleLanguageClick}
></IconClick>
<div className="relative">
{showLanguageMenu && (
<div>
<div className="absolute top-10 right-0 rounded-md shadow-md flex flex-col gap-2">
<GhostButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("en-US")}
>
English
</GhostButton>
<GhostButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("zh-CN")}
>
</GhostButton>
</div>
</div>
)}
</div></>
);
}

View File

@@ -0,0 +1,76 @@
"use client";
import { GhostLightButton } from "@/design-system/base/button";
import { useState } from "react";
import { Languages } from "lucide-react";
export function LanguageSettings() {
const [showLanguageMenu, setShowLanguageMenu] = useState(false);
const handleLanguageClick = () => {
setShowLanguageMenu((prev) => !prev);
};
const setLocale = async (locale: string) => {
document.cookie = `locale=${locale}`;
window.location.reload();
};
return (
<>
<Languages onClick={handleLanguageClick} size={28} className="text-white hover:text-white/80" />
<div className="relative">
{showLanguageMenu && (
<div>
<div className="absolute top-10 right-0 rounded-md shadow-md flex flex-col gap-2">
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("en-US")}
>
English
</GhostLightButton>
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("zh-CN")}
>
</GhostLightButton>
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("ja-JP")}
>
</GhostLightButton>
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("ko-KR")}
>
</GhostLightButton>
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("de-DE")}
>
Deutsch
</GhostLightButton>
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("fr-FR")}
>
Français
</GhostLightButton>
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("it-IT")}
>
Italiano
</GhostLightButton>
<GhostLightButton
className="w-full bg-[#35786f]"
onClick={() => setLocale("ug-CN")}
>
ئۇيغۇرچە
</GhostLightButton>
</div>
</div>
)}
</div></>
);
}

View File

@@ -1,11 +1,11 @@
import Image from "next/image"; import Image from "next/image";
import IMAGES from "@/config/images"; import { IMAGES } from "@/config/images";
import { Folder, Home } from "lucide-react"; import { Folder, Home, User } from "lucide-react";
import LanguageSettings from "../LanguageSettings"; import { LanguageSettings } from "./LanguageSettings";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { headers } from "next/headers"; import { headers } from "next/headers";
import { getTranslations } from "next-intl/server"; import { getTranslations } from "next-intl/server";
import GhostButton from "../ui/buttons/GhostButton"; import { GhostLightButton } from "@/design-system/base/button";
export async function Navbar() { export async function Navbar() {
const t = await getTranslations("navbar"); const t = await getTranslations("navbar");
@@ -14,46 +14,57 @@ export async function Navbar() {
}); });
return ( return (
<div className="flex justify-between items-center w-full h-16 px-8 bg-[#35786f] text-white"> <div className="flex justify-between items-center w-full h-16 px-4 md:px-8 bg-[#35786f] text-white">
<GhostButton href="/" className="text-xl border-b hidden md:block"> <GhostLightButton href="/" className="border-b hidden! md:block!" size="md">
{t("title")} {t("title")}
</GhostButton> </GhostLightButton>
<GhostButton className="block md:hidden" href={"/"}> <GhostLightButton className="block! md:hidden!" size="md" href={"/"}>
<Home /> <Home size={20} />
</GhostButton> </GhostLightButton>
<div className="flex text-xl gap-0.5 justify-center items-center flex-wrap"> <div className="flex gap-0.5 justify-center items-center flex-wrap">
<GhostButton <LanguageSettings />
className="md:hidden block" <GhostLightButton
className="md:hidden! block!"
size="md"
href="https://github.com/GoddoNebianU/learn-languages" href="https://github.com/GoddoNebianU/learn-languages"
> >
<Image <Image
src={IMAGES.github_mark_white} src={IMAGES.github_mark_white}
alt="GitHub" alt="GitHub"
width={24} width={20}
height={24} height={20}
/> />
</GhostButton> </GhostLightButton>
<LanguageSettings /> <GhostLightButton href="/folders" className="md:block! hidden!" size="md">
<GhostButton href="/folders" className="md:block hidden">
{t("folders")} {t("folders")}
</GhostButton> </GhostLightButton>
<GhostButton href="/folders" className="md:hidden block"> <GhostLightButton href="/folders" className="md:hidden! block!" size="md">
<Folder /> <Folder size={20} />
</GhostButton> </GhostLightButton>
{ <GhostLightButton
(() => { className="hidden! md:block!"
return session && size="md"
<GhostButton href="/profile">{t("profile")}</GhostButton>
|| <GhostButton href="/auth">{t("sign_in")}</GhostButton>;
})()
}
<GhostButton
className="hidden md:block"
href="https://github.com/GoddoNebianU/learn-languages" href="https://github.com/GoddoNebianU/learn-languages"
> >
{t("sourceCode")} {t("sourceCode")}
</GhostButton> </GhostLightButton>
{
(() => {
return session &&
<>
<GhostLightButton href="/profile" className="hidden! md:block!" size="md">{t("profile")}</GhostLightButton>
<GhostLightButton href="/profile" className="md:hidden! block!" size="md">
<User size={20} />
</GhostLightButton>
</>
|| <>
<GhostLightButton href="/auth" className="hidden! md:block!" size="md">{t("sign_in")}</GhostLightButton>
<GhostLightButton href="/auth" className="md:hidden! block!" size="md">
<User size={20} />
</GhostLightButton>
</>;
})()
}
</div> </div>
</div> </div>
); );

View File

@@ -0,0 +1,21 @@
/**
* CardList - 可滚动的卡片列表容器
*
* 使用 Design System 重写的卡片列表组件
*/
import { VStack } from "@/design-system/layout/stack";
interface CardListProps {
children: React.ReactNode;
className?: string;
}
export function CardList({ children, className = "" }: CardListProps) {
return (
<div className={`max-h-96 overflow-y-auto rounded-lg border-2 border-gray-200 ${className}`}>
<VStack gap={0}>
{children}
</VStack>
</div>
);
}

View File

@@ -1,14 +1,22 @@
/**
* Container - 容器组件
*
* 使用 Design System 重写的容器组件
*/
import { Container as DSContainer } from "@/design-system/layout/container";
import { Card } from "@/design-system/base/card";
interface ContainerProps { interface ContainerProps {
children?: React.ReactNode; children?: React.ReactNode;
className?: string; className?: string;
} }
export default function Container({ children, className }: ContainerProps) { export function Container({ children, className = "" }: ContainerProps) {
return ( return (
<div <DSContainer size="2xl" className={`mx-auto ${className}`}>
className={`w-full max-w-2xl mx-auto bg-white border border-gray-200 rounded-2xl ${className}`} <Card variant="bordered" padding="md">
>
{children} {children}
</div> </Card>
</DSContainer>
); );
} }

View File

@@ -1,28 +0,0 @@
interface Props {
ref?: React.Ref<HTMLInputElement>;
placeholder?: string;
type?: string;
className?: string;
name?: string;
defaultValue?: string;
}
export default function Input({
ref,
placeholder = "",
type = "text",
className = "",
name = "",
defaultValue = "",
}: Props) {
return (
<input
ref={ref}
placeholder={placeholder}
type={type}
className={`block focus:outline-none border-b-2 border-gray-600 ${className}`}
name={name}
defaultValue={defaultValue}
/>
);
}

View File

@@ -0,0 +1,80 @@
/**
* LocaleSelector - 语言选择器组件
*
* 使用 Design System 重写的语言选择器组件
*/
import { useTranslations } from "next-intl";
import { useState } from "react";
import { Input } from "@/design-system/base/input";
import { Select } from "@/design-system/base/select";
import { VStack } from "@/design-system/layout/stack";
const COMMON_LANGUAGES = [
{ label: "chinese", value: "chinese" },
{ label: "english", value: "english" },
{ label: "italian", value: "italian" },
{ label: "japanese", value: "japanese" },
{ label: "korean", value: "korean" },
{ label: "french", value: "french" },
{ label: "german", value: "german" },
{ label: "spanish", value: "spanish" },
{ label: "portuguese", value: "portuguese" },
{ label: "russian", value: "russian" },
{ label: "other", value: "other" },
];
interface LocaleSelectorProps {
value: string;
onChange: (val: string) => void;
}
export function LocaleSelector({ value, onChange }: LocaleSelectorProps) {
const t = useTranslations();
const [customInput, setCustomInput] = useState("");
const isCommonLanguage = COMMON_LANGUAGES.some((l) => l.value === value && l.value !== "other");
const showCustomInput = value === "other" || !isCommonLanguage;
// 计算输入框的值:如果是"other"使用自定义输入,否则使用外部传入的值
const inputValue = value === "other" ? customInput : value;
// 处理自定义输入
const handleCustomInputChange = (inputValue: string) => {
setCustomInput(inputValue);
onChange(inputValue);
};
// 当选择常见语言或"其他"时
const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const selectedValue = e.target.value;
if (selectedValue === "other") {
setCustomInput("");
onChange("other");
} else {
onChange(selectedValue);
}
};
return (
<VStack gap={2}>
<Select
value={isCommonLanguage ? value : "other"}
onChange={handleSelectChange}
>
{COMMON_LANGUAGES.map((lang) => (
<option key={lang.value} value={lang.value}>
{t(`translator.${lang.label}`)}
</option>
))}
</Select>
{showCustomInput && (
<Input
type="text"
value={inputValue}
onChange={(e) => handleCustomInputChange(e.target.value)}
placeholder={t("folder_id.enterLanguageName")}
variant="bordered"
/>
)}
</VStack>
);
}

View File

@@ -0,0 +1,25 @@
/**
* PageHeader - 页面标题组件
*
* 使用 Design System 重写的页面标题组件
*/
import { VStack } from "@/design-system/layout/stack";
interface PageHeaderProps {
title: string;
subtitle?: string;
className?: string;
}
export function PageHeader({ title, subtitle, className = "" }: PageHeaderProps) {
return (
<VStack gap={2} className={`mb-6 ${className}`}>
<h1 className="text-2xl md:text-3xl font-bold text-gray-800">
{title}
</h1>
{subtitle && (
<p className="text-sm text-gray-500">{subtitle}</p>
)}
</VStack>
);
}

View File

@@ -0,0 +1,64 @@
/**
* PageLayout - 页面布局组件
*
* 使用 Design System 重写的页面布局组件
*/
import { Card } from "@/design-system/base/card";
import { Container } from "@/design-system/layout/container";
type PageLayoutVariant = "centered-card" | "full-width" | "fullscreen";
interface PageLayoutProps {
children: React.ReactNode;
className?: string;
variant?: PageLayoutVariant;
align?: "center" | "start" | "end";
}
const alignClasses = {
center: "items-center",
start: "items-start",
end: "items-end",
};
export function PageLayout({
children,
className = "",
variant = "centered-card",
align = "center",
}: PageLayoutProps) {
// 居中卡片布局
if (variant === "centered-card") {
return (
<div className={`min-h-[calc(100vh-64px)] bg-primary-500 flex ${alignClasses[align]} justify-center px-4 py-8 ${className}`}>
<div className="w-full max-w-2xl">
<Card padding="lg" className="p-6 md:p-8">
{children}
</Card>
</div>
</div>
);
}
// 全宽布局
if (variant === "full-width") {
return (
<div className={`min-h-[calc(100vh-64px)] bg-primary-500 px-4 py-8 ${className}`}>
<Container size="2xl">
{children}
</Container>
</div>
);
}
// 全屏布局
if (variant === "fullscreen") {
return (
<div className={`min-h-[calc(100vh-64px)] bg-primary-500 ${className}`}>
{children}
</div>
);
}
return null;
}

View File

@@ -0,0 +1,45 @@
"use client";
import React from "react";
interface RangeInputProps {
value: number;
max: number;
onChange: (value: number) => void;
disabled?: boolean;
className?: string;
min?: number;
}
export function RangeInput({
value,
max,
onChange,
disabled = false,
className = "",
min = 0,
}: RangeInputProps) {
const handleChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = parseInt(event.target.value);
onChange(newValue);
}, [onChange]);
const progressPercentage = ((value - min) / (max - min)) * 100;
return (
<input
type="range"
min={min}
max={max}
value={value}
onChange={handleChange}
disabled={disabled}
className={`w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary-500 ${
disabled ? "opacity-50 cursor-not-allowed" : ""
} ${className}`}
style={{
background: `linear-gradient(to right, #374151 0%, #374151 ${progressPercentage}%, #e5e7eb ${progressPercentage}%, #e5e7eb 100%)`
}}
/>
);
}

View File

@@ -1,28 +0,0 @@
import PlainButton, { ButtonType } from "./PlainButton";
export default function DarkButton({
onClick,
className,
selected,
children,
type = "button",
disabled
}: {
onClick?: (() => void) | undefined;
className?: string;
selected?: boolean;
children?: React.ReactNode;
type?: ButtonType;
disabled?: boolean;
}) {
return (
<PlainButton
onClick={onClick}
className={`hover:bg-gray-100 text-black ${selected ? "bg-gray-100" : "bg-white"} ${className}`}
type={type}
disabled={disabled}
>
{children}
</PlainButton>
);
}

View File

@@ -1,27 +0,0 @@
import Link from "next/link";
export type ButtonType = "button" | "submit" | "reset" | undefined;
export default function GhostButton({
onClick,
className,
children,
type = "button",
href
}: {
onClick?: () => void;
className?: string;
children?: React.ReactNode;
type?: ButtonType;
href?: string;
}) {
return (
<button
onClick={onClick}
className={`rounded hover:bg-black/30 p-2 ${className}`}
type={type}
>
{href ? <Link href={href}>{children}</Link> : children}
</button>
);
}

View File

@@ -1,29 +0,0 @@
import Image from "next/image";
interface IconClickProps {
src: string;
alt: string;
onClick?: () => void;
className?: string;
size?: number;
disableOnHoverBgChange?: boolean;
}
export default function IconClick({
src,
alt,
onClick = () => {},
className = "",
size = 32,
disableOnHoverBgChange = false,
}: IconClickProps) {
return (
<>
<div
onClick={onClick}
className={`${disableOnHoverBgChange ? "" : "hover:bg-gray-200"} hover:cursor-pointer rounded-3xl w-[${size}px] h-[${size}px] flex justify-center items-center ${className}`}
>
<Image src={src} width={size - 5} height={size - 5} alt={alt}></Image>
</div>
</>
);
}

View File

@@ -1,28 +0,0 @@
import PlainButton, { ButtonType } from "../buttons/PlainButton";
export default function LightButton({
onClick,
className,
selected,
children,
type = "button",
disabled
}: {
onClick?: (() => void) | undefined;
className?: string;
selected?: boolean;
children?: React.ReactNode;
type?: ButtonType;
disabled?: boolean;
}) {
return (
<PlainButton
onClick={onClick}
className={`hover:bg-gray-100 text-black ${selected ? "bg-gray-100" : "bg-white"} ${className}`}
type={type}
disabled={disabled}
>
{children}
</PlainButton>
);
}

View File

@@ -1,26 +0,0 @@
export type ButtonType = "button" | "submit" | "reset" | undefined;
export default function PlainButton({
onClick,
className,
children,
type = "button",
disabled
}: {
onClick?: () => void;
className?: string;
children?: React.ReactNode;
type?: ButtonType;
disabled?: boolean;
}) {
return (
<button
onClick={onClick}
className={`px-2 py-1 rounded shadow font-bold hover:cursor-pointer ${className}`}
type={type}
disabled={disabled}
>
{children}
</button>
);
}

View File

@@ -1,16 +0,0 @@
"use client";
interface ACardProps {
children?: React.ReactNode;
className?: string;
}
export default function ACard({ children, className }: ACardProps) {
return (
<div
className={`${className} w-[95dvw] md:w-[61vw] h-96 p-2 md:shadow-2xl rounded-xl`}
>
{children}
</div>
);
}

View File

@@ -1,12 +0,0 @@
"use client";
interface BCardProps {
children?: React.ReactNode;
className?: string;
}
export default function BCard({ children, className }: BCardProps) {
return (
<div className={`${className} rounded-xl p-2 shadow-xl`}>{children}</div>
);
}

View File

@@ -0,0 +1,37 @@
// 统一的 UI 组件导出
// 可以从 '@/components/ui' 导入所有组件
// Design System 组件(向后兼容)
export { Input, type InputVariant, type InputProps } from '@/design-system/base/input';
export { Select, type SelectVariant, type SelectSize, type SelectProps } from '@/design-system/base/select';
export { Textarea, type TextareaVariant, type TextareaProps } from '@/design-system/base/textarea';
export { Card, type CardVariant, type CardPadding, type CardProps } from '@/design-system/base/card';
export {
Button,
PrimaryButton,
SecondaryButton,
LightButton,
SuccessButton,
WarningButton,
ErrorButton,
GhostButton,
GhostLightButton,
OutlineButton,
LinkButton,
IconButton,
IconClick,
CircleButton,
CircleToggleButton,
DashedButton,
type ButtonVariant,
type ButtonSize,
type ButtonProps
} from '@/design-system/base/button';
// 业务特定组件
export { RangeInput } from './RangeInput';
export { Container } from './Container';
export { PageLayout } from './PageLayout';
export { PageHeader } from './PageHeader';
export { CardList } from './CardList';
export { LocaleSelector } from './LocaleSelector';

View File

@@ -1,2 +1,11 @@
export const SUPPORTED_LOCALES = ["en-US", "zh-CN"]; export const SUPPORTED_LOCALES = [
"en-US",
"zh-CN",
"ja-JP",
"ko-KR",
"de-DE",
"fr-FR",
"it-IT",
"ug-CN",
];
export const DEFAULT_LOCALE = "en-US"; export const DEFAULT_LOCALE = "en-US";

View File

@@ -21,4 +21,4 @@ const IMAGES = {
github_mark_white: "/images/github-mark/github-mark-white.svg", github_mark_white: "/images/github-mark/github-mark-white.svg",
}; };
export default IMAGES; export { IMAGES };

File diff suppressed because it is too large Load Diff

585
src/design-system/README.md Normal file
View File

@@ -0,0 +1,585 @@
# Design System
完整的设计系统,提供可复用的 UI 组件和设计令牌,确保整个应用的一致性。
## 目录结构
```
src/design-system/
├── tokens/ # 设计令牌(颜色、间距、字体等)
├── lib/ # 工具函数
├── base/ # 基础组件
│ ├── button/
│ ├── input/
│ ├── textarea/
│ ├── card/
│ ├── checkbox/
│ ├── radio/
│ ├── switch/
│ └── select/
├── feedback/ # 反馈组件
│ ├── alert/
│ ├── progress/
│ ├── skeleton/
│ └── toast/
├── overlay/ # 覆盖组件
│ └── modal/
├── data-display/ # 数据展示组件
│ ├── badge/
│ └── divider/
├── layout/ # 布局组件
│ ├── container/
│ ├── grid/
│ └── stack/
├── navigation/ # 导航组件
│ └── tabs/
└── index.ts # 统一导出
```
## 快速开始
### 安装依赖
```bash
pnpm add class-variance-authority clsx tailwind-merge
```
### 导入组件
```tsx
// 方式 1: 从主入口导入(简单但 tree-shaking 较差)
import { Button, Input, Card } from '@/design-system';
// 方式 2: 从子路径导入(更好的 tree-shaking
import { Button } from '@/design-system/base/button';
import { Input } from '@/design-system/base/input';
import { Card } from '@/design-system/base/card';
```
### 使用组件
```tsx
import { Button, Card } from '@/design-system';
export function MyComponent() {
return (
<Card>
<h1>标题</h1>
<p>内容</p>
<Button variant="primary">点击我</Button>
</Card>
);
}
```
## 组件列表
### 基础组件
| 组件 | 说明 | 状态 |
|------|------|------|
| [Button](#button) | 按钮 | ✅ |
| [Input](#input) | 输入框 | ✅ |
| [Textarea](#textarea) | 多行文本输入 | ✅ |
| [Card](#card) | 卡片容器 | ✅ |
| [Checkbox](#checkbox) | 复选框 | ✅ |
| [Radio](#radio) | 单选按钮 | ✅ |
| [Switch](#switch) | 开关 | ✅ |
| [Select](#select) | 下拉选择框 | ✅ |
### 反馈组件
| 组件 | 说明 | 状态 |
|------|------|------|
| [Alert](#alert) | 警告提示 | ✅ |
| [Progress](#progress) | 进度条 | ✅ |
| [Skeleton](#skeleton) | 骨架屏 | ✅ |
| [Toast](#toast) | 通知提示 | ✅ |
### 覆盖组件
| 组件 | 说明 | 状态 |
|------|------|------|
| [Modal](#modal) | 模态框 | ✅ |
### 数据展示组件
| 组件 | 说明 | 状态 |
|------|------|------|
| [Badge](#badge) | 徽章 | ✅ |
| [Divider](#divider) | 分隔线 | ✅ |
### 布局组件
| 组件 | 说明 | 状态 |
|------|------|------|
| [Container](#container) | 容器 | ✅ |
| [Grid](#grid) | 网格布局 | ✅ |
| [Stack](#stack) | 堆叠布局 | ✅ |
### 导航组件
| 组件 | 说明 | 状态 |
|------|------|------|
| [Tabs](#tabs) | 标签页 | ✅ |
## 组件 API
### Button
按钮组件,支持多种变体和尺寸。
```tsx
import { Button } from '@/design-system';
<Button variant="primary" size="md" onClick={handleClick}>
点击我
</Button>
```
**变体 (variant)**: `primary` | `secondary` | `success` | `warning` | `error` | `ghost` | `outline` | `link`
**尺寸 (size)**: `sm` | `md` | `lg`
**快捷组件**: `PrimaryButton`, `SecondaryButton`, `SuccessButton`, `WarningButton`, `ErrorButton`, `GhostButton`, `OutlineButton`, `LinkButton`
### Input
输入框组件。
```tsx
import { Input } from '@/design-system';
<Input
variant="bordered"
placeholder="请输入内容"
error={hasError}
/>
```
**变体 (variant)**: `default` | `bordered` | `filled` | `search`
**尺寸 (size)**: `sm` | `md` | `lg`
### Textarea
多行文本输入组件。
```tsx
import { Textarea } from '@/design-system';
<Textarea
variant="bordered"
placeholder="请输入内容"
rows={4}
/>
```
**变体 (variant)**: `default` | `bordered` | `filled`
### Card
卡片容器组件。
```tsx
import { Card, CardHeader, CardTitle, CardBody, CardFooter } from '@/design-system';
<Card>
<CardHeader>
<CardTitle>标题</CardTitle>
</CardHeader>
<CardBody>
<p>内容</p>
</CardBody>
<CardFooter>
<Button>确定</Button>
</CardFooter>
</Card>
```
**变体 (variant)**: `default` | `bordered` | `elevated` | `flat`
**内边距 (padding)**: `none` | `xs` | `sm` | `md` | `lg` | `xl`
### Checkbox
复选框组件。
```tsx
import { Checkbox } from '@/design-system';
<Checkbox checked={checked} onChange={setChecked}>
同意条款
</Checkbox>
```
### Radio
单选按钮组件。
```tsx
import { Radio, RadioGroup } from '@/design-system';
<RadioGroup name="choice" value={value} onChange={setValue}>
<Radio value="1">选项 1</Radio>
<Radio value="2">选项 2</Radio>
</RadioGroup>
```
### Switch
开关组件。
```tsx
import { Switch } from '@/design-system';
<Switch checked={enabled} onChange={setEnabled} />
```
### Alert
警告提示组件。
```tsx
import { Alert } from '@/design-system';
<Alert variant="success" title="成功">
操作成功完成
</Alert>
```
**变体 (variant)**: `info` | `success` | `warning` | `error`
### Progress
进度条组件。
```tsx
import { Progress } from '@/design-system';
<Progress value={60} showLabel />
```
### Skeleton
骨架屏组件。
```tsx
import { Skeleton, TextSkeleton, CardSkeleton } from '@/design-system';
<Skeleton className="h-4 w-32" />
<TextSkeleton lines={3} />
<CardSkeleton />
```
### Toast
通知提示组件(基于 sonner
```tsx
import { toast } from '@/design-system';
toast.success("操作成功!");
toast.error("发生错误");
toast.promise(promise, {
loading: "加载中...",
success: "加载成功",
error: "加载失败",
});
```
### Modal
模态框组件。
```tsx
import { Modal } from '@/design-system';
<Modal open={open} onClose={() => setOpen(false)}>
<Modal.Header>
<Modal.Title>标题</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>内容</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={() => setOpen(false)}>
取消
</Button>
<Button variant="primary">确定</Button>
</Modal.Footer>
</Modal>
```
### Badge
徽章组件。
```tsx
import { Badge } from '@/design-system';
<Badge variant="success">成功</Badge>
<Badge dot />
```
**变体 (variant)**: `default` | `primary` | `success` | `warning` | `error` | `info`
### Divider
分隔线组件。
```tsx
import { Divider } from '@/design-system';
<Divider />
<Divider>或者</Divider>
<Divider orientation="vertical" />
```
### Container
容器组件。
```tsx
import { Container } from '@/design-system';
<Container size="lg" padding="xl">
<p>内容</p>
</Container>
```
### Grid
网格布局组件。
```tsx
import { Grid } from '@/design-system';
<Grid cols={3} gap={4}>
<div>项目 1</div>
<div>项目 2</div>
<div>项目 3</div>
</Grid>
```
### Stack
堆叠布局组件。
```tsx
import { Stack, VStack, HStack } from '@/design-system';
<VStack gap={4}>
<div>项目 1</div>
<div>项目 2</div>
</VStack>
```
### Tabs
标签页组件。
```tsx
import { Tabs } from '@/design-system';
<Tabs value={activeTab} onValueChange={setActiveTab}>
<Tabs.List>
<Tabs.Trigger value="tab1">标签 1</Tabs.Trigger>
<Tabs.Trigger value="tab2">标签 2</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="tab1">
<p>内容 1</p>
</Tabs.Content>
<Tabs.Content value="tab2">
<p>内容 2</p>
</Tabs.Content>
</Tabs>
```
## 设计令牌
### 颜色
```tsx
import { colors } from '@/design-system/tokens';
// 主色
colors.primary.500 // #35786f
// 语义色
colors.success.500 // #22c55e
colors.warning.500 // #f59e0b
colors.error.500 // #ef4444
colors.info.500 // #3b82f6
```
在组件中使用:
```tsx
<div className="bg-primary-500 text-white">主色背景</div>
<div className="text-success-600">成功文本</div>
```
### 间距
基于 8pt 网格系统:
```tsx
<div className="p-4"> // 16px
<div className="p-6"> // 24px
<div className="p-8"> // 32px
```
### 字体
```tsx
<div className="text-sm">小文本</div>
<div className="text-base">正常文本</div>
<div className="text-lg">大文本</div>
<div className="font-semibold">半粗体</div>
<div className="font-bold">粗体</div>
```
### 圆角
```tsx
<div className="rounded-lg"> // 8px
<div className="rounded-xl"> // 12px
<div className="rounded-2xl"> // 16px
```
### 阴影
```tsx
<div className="shadow-sm"> // 小阴影
<div className="shadow-md"> // 中阴影
<div className="shadow-lg"> // 大阴影
<div className="shadow-xl"> // 超大阴影
```
## 工具函数
### cn
合并 Tailwind CSS 类名的工具函数。
```tsx
import { cn } from '@/design-system';
const className = cn(
'base-class',
isActive && 'active-class',
'another-class'
);
```
## 最佳实践
### 1. 组件导入
对于更好的 tree-shaking建议从子路径导入
```tsx
// ✅ 推荐
import { Button } from '@/design-system/base/button';
// ❌ 不推荐(但也可以)
import { Button } from '@/design-system';
```
### 2. 样式覆盖
使用 `className` 属性覆盖样式:
```tsx
<Button className="w-full">全宽按钮</Button>
```
### 3. 组合组件
利用组件组合来构建复杂 UI
```tsx
<Card>
<CardHeader>
<CardTitle>标题</CardTitle>
</CardHeader>
<CardBody>
<VStack gap={4}>
<Input placeholder="输入框" />
<Button>提交</Button>
</VStack>
</CardBody>
</Card>
```
### 4. 可访问性
所有组件都内置了可访问性支持:
- 正确的 ARIA 属性
- 键盘导航支持
- 焦点管理
- 屏幕阅读器友好
## 迁移指南
### 从旧组件迁移
旧的组件路径:
```tsx
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
```
新的组件路径:
```tsx
import { Button } from '@/design-system/base/button';
import { Input } from '@/design-system/base/input';
```
### API 变化
大部分 API 保持兼容,但有以下变化:
1. **颜色不再使用硬编码值**
```tsx
// 旧
style={{ backgroundColor: '#35786f' }}
// 新
className="bg-primary-500"
```
2. **变体命名更加一致**
```tsx
// 旧
<Button variant="icon" />
// 新
<Button variant="ghost" />
```
3. **新增语义色变体**
```tsx
<Button variant="success">成功</Button>
<Button variant="warning">警告</Button>
<Button variant="error">错误</Button>
```
## 贡献
添加新组件时,请遵循以下规范:
1. 在对应的目录下创建组件
2. 使用 `cva` 定义变体样式
3. 使用 `forwardRef` 支持 ref 转发
4. 添加完整的 TypeScript 类型
5. 编写详细的 JSDoc 注释和示例
6. 在导出文件中添加导出
## 许可证
AGPL-3.0-only

View File

@@ -0,0 +1,351 @@
"use client";
import React from "react";
import Link from "next/link";
import Image from "next/image";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/design-system/lib/utils";
/**
* Button 组件
*
* Design System 中的按钮组件,支持多种变体、尺寸和状态。
* 自动处理 Link/button 切换,支持图标和加载状态。
*
* @example
* ```tsx
* // Primary 按钮
* <Button variant="primary" onClick={handleClick}>
* 点击我
* </Button>
*
* // 带图标的按钮
* <Button variant="secondary" leftIcon={<Icon />}>
* 带图标
* </Button>
*
* // 作为链接使用
* <Button variant="primary" href="/path">
* 链接按钮
* </Button>
*
* // 加载状态
* <Button variant="primary" loading>
* 提交中...
* </Button>
* ```
*/
/**
* 按钮变体样式
*/
const buttonVariants = cva(
// 基础样式
"inline-flex items-center justify-center gap-2 rounded-md font-semibold shadow transition-all duration-250 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
primary: "bg-primary-500 text-white hover:bg-primary-600 shadow-md",
secondary: "bg-gray-100 text-gray-900 hover:bg-gray-200 shadow-sm",
success: "bg-success-500 text-white hover:bg-success-600 shadow-md",
warning: "bg-warning-500 text-white hover:bg-warning-600 shadow-md",
error: "bg-error-500 text-white hover:bg-error-600 shadow-md",
ghost: "bg-transparent text-gray-700 hover:bg-gray-100 shadow-none",
"ghost-light": "bg-transparent text-white hover:bg-white/10 shadow-none",
outline: "border-2 border-gray-300 text-gray-700 hover:bg-gray-50 shadow-none",
link: "text-primary-500 hover:text-primary-600 hover:underline shadow-none px-0",
},
size: {
sm: "h-8 px-3 text-sm",
md: "h-10 px-4 text-base",
lg: "h-12 px-6 text-lg",
},
fullWidth: {
true: "w-full",
false: "",
},
},
compoundVariants: [
// 链接变体不应用高度和圆角
{
variant: "link",
size: "sm",
className: "h-auto px-0",
},
{
variant: "link",
size: "md",
className: "h-auto px-0",
},
{
variant: "link",
size: "lg",
className: "h-auto px-0",
},
],
defaultVariants: {
variant: "secondary",
size: "md",
fullWidth: false,
},
}
);
export type ButtonVariant = VariantProps<typeof buttonVariants>["variant"];
export type ButtonSize = VariantProps<typeof buttonVariants>["size"];
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
// 内容
children?: React.ReactNode;
// 导航
href?: string;
openInNewTab?: boolean;
// 图标
leftIcon?: React.ReactNode;
rightIcon?: React.ReactNode;
iconSrc?: string; // For Next.js Image icons
iconAlt?: string;
// 状态
loading?: boolean;
selected?: boolean;
// 样式
className?: string;
}
/**
* Button 组件
*/
export function Button({
variant = "secondary",
size = "md",
fullWidth = false,
href,
openInNewTab = false,
iconSrc,
iconAlt,
leftIcon,
rightIcon,
children,
className,
loading = false,
selected = false,
disabled,
type = "button",
...props
}: ButtonProps) {
// 确保 size 有默认值
const actualSize = size ?? "md";
// 计算样式
const computedClass = cn(
buttonVariants({ variant, size: actualSize, fullWidth }),
selected && variant === "secondary" && "bg-gray-200",
className
);
// 图标尺寸映射
const iconSize = { sm: 14, md: 16, lg: 20 }[actualSize];
// 渲染 SVG 图标
const renderSvgIcon = (icon: React.ReactNode, position: "left" | "right") => {
if (!icon) return null;
return (
<span className={`flex items-center shrink-0 ${position === "left" ? "-ml-1 mr-2" : "-mr-1 ml-2"}`}>
{icon}
</span>
);
};
// 渲染 Next.js Image 图标
const renderImageIcon = () => {
if (!iconSrc) return null;
return (
<Image
src={iconSrc}
width={iconSize}
height={iconSize}
alt={iconAlt || "icon"}
className="shrink-0"
/>
);
};
// 渲染加载图标
const renderLoadingIcon = () => {
if (!loading) return null;
return (
<svg
className="animate-spin h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
);
};
// 组装内容
const content = (
<>
{loading && renderLoadingIcon()}
{renderImageIcon()}
{renderSvgIcon(leftIcon, "left")}
{children}
{renderSvgIcon(rightIcon, "right")}
</>
);
// 如果提供了 href渲染为 Link
if (href) {
return (
<Link
href={href}
className={computedClass}
target={openInNewTab ? "_blank" : undefined}
rel={openInNewTab ? "noopener noreferrer" : undefined}
>
{content}
</Link>
);
}
// 否则渲染为 button
return (
<button
type={type}
disabled={disabled || loading}
className={computedClass}
{...props}
>
{content}
</button>
);
}
/**
* 预定义的按钮快捷组件
*/
export const PrimaryButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="primary" {...props} />
);
export const SecondaryButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="secondary" {...props} />
);
// LightButton: 次要按钮的别名(向后兼容)
export const LightButton = SecondaryButton;
export const SuccessButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="success" {...props} />
);
export const WarningButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="warning" {...props} />
);
export const ErrorButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="error" {...props} />
);
export const GhostButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="ghost" {...props} />
);
// GhostLightButton: 透明按钮(白色文字,用于深色背景)
export const GhostLightButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="ghost-light" {...props} />
);
export const OutlineButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="outline" {...props} />
);
export const LinkButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="link" {...props} />
);
// ========== 其他便捷组件 ==========
// IconButton: SVG 图标按钮(使用 ghost 变体)
export const IconButton = (props: Omit<ButtonProps, "variant"> & { icon?: React.ReactNode }) => {
const { icon, ...rest } = props;
return <Button variant="ghost" leftIcon={icon} {...rest} />;
};
// IconClick: 图片图标按钮(支持 Next.js Image
export const IconClick = (props: Omit<ButtonProps, "variant"> & {
src?: string;
alt?: string;
size?: number | "sm" | "md" | "lg";
disableOnHoverBgChange?: boolean;
}) => {
const { src, alt, size, disableOnHoverBgChange, className, ...rest } = props;
let buttonSize: "sm" | "md" | "lg" = "md";
if (typeof size === "number") {
if (size <= 20) buttonSize = "sm";
else if (size >= 32) buttonSize = "lg";
} else if (typeof size === "string") {
buttonSize = (size === "sm" || size === "md" || size === "lg") ? size : "md";
}
const hoverClass = disableOnHoverBgChange ? "hover:bg-black/30" : "";
return (
<Button
variant="ghost"
iconSrc={src}
iconAlt={alt}
size={buttonSize}
className={`${hoverClass} ${className || ""}`}
{...rest}
/>
);
};
// CircleButton: 圆形图标按钮
export const CircleButton = (props: Omit<ButtonProps, "variant"> & { icon?: React.ReactNode }) => {
const { icon, className, ...rest } = props;
return <Button variant="ghost" leftIcon={icon} className={`rounded-full ${className || ""}`} {...rest} />;
};
// CircleToggleButton: 带选中状态的圆形切换按钮
export const CircleToggleButton = (props: Omit<ButtonProps, "variant"> & { selected?: boolean }) => {
const { selected, className, children, ...rest } = props;
const selectedClass = selected
? "bg-primary-500 text-white"
: "bg-gray-200 text-gray-600 hover:bg-gray-300";
return (
<Button
variant="secondary"
className={`rounded-full px-3 py-1 text-sm transition-colors ${selectedClass} ${className || ""}`}
{...rest}
>
{children}
</Button>
);
};
// DashedButton: 虚线边框按钮(使用 outline 变体近似)
export const DashedButton = (props: Omit<ButtonProps, "variant">) => (
<Button variant="outline" className="border-dashed" {...props} />
);

View File

@@ -0,0 +1 @@
export * from './button';

View File

@@ -0,0 +1,198 @@
import React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/design-system/lib/utils";
/**
* Card 卡片组件
*
* Design System 中的卡片容器组件,提供统一的内容包装样式。
*
* @example
* ```tsx
* // 默认卡片
* <Card>
* <p>卡片内容</p>
* </Card>
*
* // 带边框的卡片
* <Card variant="bordered" padding="lg">
* <p>带边框的内容</p>
* </Card>
*
* // 无内边距卡片
* <Card padding="none">
* <img src="image.jpg" alt="完全填充的图片" />
* </Card>
*
* // 可点击的卡片
* <Card clickable onClick={handleClick}>
* <p>点击我</p>
* </Card>
* ```
*/
/**
* 卡片变体样式
*/
const cardVariants = cva(
// 基础样式
"rounded-lg bg-white transition-all duration-250",
{
variants: {
variant: {
default: "shadow-xl",
bordered: "border-2 border-gray-200 shadow-sm",
elevated: "shadow-2xl",
flat: "border border-gray-200 shadow-none",
},
padding: {
none: "",
xs: "p-3",
sm: "p-4",
md: "p-6",
lg: "p-8",
xl: "p-10",
},
clickable: {
true: "cursor-pointer hover:shadow-primary/25 hover:-translate-y-0.5 active:translate-y-0",
false: "",
},
},
defaultVariants: {
variant: "default",
padding: "md",
clickable: false,
},
}
);
export type CardVariant = VariantProps<typeof cardVariants>["variant"];
export type CardPadding = VariantProps<typeof cardVariants>["padding"];
export interface CardProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof cardVariants> {
// 子元素
children: React.ReactNode;
}
/**
* Card 卡片组件
*/
export function Card({
variant = "default",
padding = "md",
clickable = false,
className,
children,
...props
}: CardProps) {
return (
<div
className={cn(cardVariants({ variant, padding, clickable }), className)}
{...props}
>
{children}
</div>
);
}
/**
* CardSection - 卡片内容区块
* 用于组织卡片内部的多个内容区块
*/
export interface CardSectionProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
noPadding?: boolean;
}
export function CardSection({
noPadding = false,
className,
children,
...props
}: CardSectionProps) {
return (
<div
className={cn(
!noPadding && "p-6",
"first:rounded-t-2xl last:rounded-b-2xl",
className
)}
{...props}
>
{children}
</div>
);
}
/**
* CardHeader - 卡片头部
*/
export interface CardHeaderProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
export function CardHeader({
className,
children,
...props
}: CardHeaderProps) {
return (
<div
className={cn("flex items-center justify-between p-6 border-b border-gray-200", className)}
{...props}
>
{children}
</div>
);
}
/**
* CardTitle - 卡片标题
*/
export interface CardTitleProps extends React.HTMLAttributes<HTMLHeadingElement> {
children: React.ReactNode;
}
export function CardTitle({
className,
children,
...props
}: CardTitleProps) {
return (
<h3
className={cn("text-lg font-semibold text-gray-900", className)}
{...props}
>
{children}
</h3>
);
}
/**
* CardBody - 卡片主体
*/
export const CardBody = CardSection;
/**
* CardFooter - 卡片底部
*/
export interface CardFooterProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
}
export function CardFooter({
className,
children,
...props
}: CardFooterProps) {
return (
<div
className={cn("flex items-center justify-end gap-2 p-6 border-t border-gray-200", className)}
{...props}
>
{children}
</div>
);
}

View File

@@ -0,0 +1 @@
export * from './card';

View File

@@ -0,0 +1,170 @@
"use client";
import React, { forwardRef } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/design-system/lib/utils";
/**
* Checkbox 复选框组件
*
* Design System 中的复选框组件,支持多种状态和尺寸。
*
* @example
* ```tsx
* // 默认复选框
* <Checkbox>同意条款</Checkbox>
*
* // 受控组件
* <Checkbox checked={checked} onChange={handleChange}>
* 同意条款
* </Checkbox>
*
* // 错误状态
* <Checkbox error>必选项</Checkbox>
* ```
*/
/**
* 复选框变体样式
*/
const checkboxVariants = cva(
// 基础样式
"peer h-4 w-4 shrink-0 rounded border-2 transition-all duration-250 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
{
variants: {
variant: {
default: "border-gray-300 checked:bg-primary-500 checked:border-primary-500",
success: "border-gray-300 checked:bg-success-500 checked:border-success-500",
warning: "border-gray-300 checked:bg-warning-500 checked:border-warning-500",
error: "border-gray-300 checked:bg-error-500 checked:border-error-500",
},
size: {
sm: "h-3.5 w-3.5",
md: "h-4 w-4",
lg: "h-5 w-5",
},
error: {
true: "border-error-500",
false: "",
},
},
defaultVariants: {
variant: "default",
size: "md",
error: false,
},
}
);
export type CheckboxVariant = VariantProps<typeof checkboxVariants>["variant"];
export type CheckboxSize = VariantProps<typeof checkboxVariants>["size"];
export interface CheckboxProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "size">,
VariantProps<typeof checkboxVariants> {
// 标签文本
label?: React.ReactNode;
// 标签位置
labelPosition?: "left" | "right";
// 自定义复选框类名
checkboxClassName?: string;
}
/**
* Checkbox 复选框组件
*/
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
(
{
variant = "default",
size = "md",
error = false,
label,
labelPosition = "right",
className,
checkboxClassName,
disabled,
...props
},
ref
) => {
const checkboxId = React.useId();
const renderCheckbox = () => (
<input
ref={ref}
type="checkbox"
id={checkboxId}
disabled={disabled}
className={cn(
checkboxVariants({ variant, size, error }),
checkboxClassName
)}
{...props}
/>
);
const renderLabel = () => {
if (!label) return null;
return (
<label
htmlFor={checkboxId}
className={cn(
"text-base font-normal leading-none",
disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",
labelPosition === "left" ? "mr-2" : "ml-2"
)}
>
{label}
</label>
);
};
if (!label) {
return renderCheckbox();
}
return (
<div className={cn("inline-flex items-center", className)}>
{labelPosition === "left" && renderLabel()}
{renderCheckbox()}
{labelPosition === "right" && renderLabel()}
</div>
);
}
);
Checkbox.displayName = "Checkbox";
/**
* CheckboxGroup - 复选框组
*/
export interface CheckboxGroupProps {
children: React.ReactNode;
label?: string;
error?: string;
required?: boolean;
className?: string;
}
export function CheckboxGroup({
children,
label,
error,
required,
className,
}: CheckboxGroupProps) {
return (
<div className={cn("space-y-2", className)}>
{label && (
<div className="text-base font-medium text-gray-900">
{label}
{required && <span className="text-error-500 ml-1">*</span>}
</div>
)}
<div className="space-y-2">{children}</div>
{error && <p className="text-sm text-error-500">{error}</p>}
</div>
);
}

View File

@@ -0,0 +1 @@
export * from './checkbox';

View File

@@ -0,0 +1 @@
export * from './input';

View File

@@ -0,0 +1,151 @@
"use client";
import React, { forwardRef } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/design-system/lib/utils";
/**
* Input 输入框组件
*
* Design System 中的输入框组件,支持多种样式变体和尺寸。
* 完全可访问,支持焦点状态和错误状态。
*
* @example
* ```tsx
* // 默认样式
* <Input placeholder="请输入内容" />
*
* // 带边框样式
* <Input variant="bordered" placeholder="带边框的输入框" />
*
* // 填充样式
* <Input variant="filled" placeholder="填充背景的输入框" />
*
* // 错误状态
* <Input variant="bordered" error placeholder="有错误的输入框" />
*
* // 禁用状态
* <Input disabled placeholder="禁用的输入框" />
* ```
*/
/**
* 输入框变体样式
*/
const inputVariants = cva(
// 基础样式
"flex w-full rounded-md border px-3 py-2 text-base transition-all duration-250 placeholder:text-gray-400 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
{
variants: {
variant: {
default: "border-b-2 border-gray-300 bg-transparent rounded-t-md",
bordered: "border-gray-300 bg-white",
filled: "border-transparent bg-gray-100",
search: "border-gray-200 bg-white pl-10 rounded-full",
},
size: {
sm: "h-9 px-3 text-sm",
md: "h-10 px-4 text-base",
lg: "h-12 px-5 text-lg",
},
error: {
true: "border-error-500 focus-visible:ring-error-500",
false: "",
},
},
compoundVariants: [
// 填充变体的错误状态
{
variant: "filled",
error: true,
className: "bg-error-50",
},
],
defaultVariants: {
variant: "default",
size: "md",
error: false,
},
}
);
export type InputVariant = VariantProps<typeof inputVariants>["variant"];
export type InputSize = VariantProps<typeof inputVariants>["size"];
export interface InputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "size">,
VariantProps<typeof inputVariants> {
// 左侧图标(通常用于搜索框)
leftIcon?: React.ReactNode;
// 右侧图标(例如清除按钮)
rightIcon?: React.ReactNode;
// 容器类名(用于包裹图标和输入框)
containerClassName?: string;
}
/**
* Input 输入框组件
*/
export const Input = forwardRef<HTMLInputElement, InputProps>(
(
{
variant = "default",
size = "md",
error = false,
className,
containerClassName,
leftIcon,
rightIcon,
type = "text",
...props
},
ref
) => {
// 如果有左侧图标,使用相对定位的容器
if (leftIcon) {
return (
<div className={cn("relative", containerClassName)}>
{/* 左侧图标 */}
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none">
{leftIcon}
</div>
{/* 输入框 */}
<input
ref={ref}
type={type}
className={cn(
inputVariants({ variant, size, error }),
leftIcon && "pl-10"
)}
{...props}
/>
{/* 右侧图标 */}
{rightIcon && (
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">
{rightIcon}
</div>
)}
</div>
);
}
// 普通输入框
return (
<div className={cn("relative", containerClassName)}>
<input
ref={ref}
type={type}
className={cn(inputVariants({ variant, size, error }), className)}
{...props}
/>
{rightIcon && (
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">
{rightIcon}
</div>
)}
</div>
);
}
);
Input.displayName = "Input";

Some files were not shown because too many files have changed in this diff Show More