Compare commits

...

7 Commits

Author SHA1 Message Date
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
85 changed files with 1268 additions and 1142 deletions

View File

@@ -35,3 +35,5 @@ build.sh
# prisma # prisma
/generated/prisma /generated/prisma
.claude

4
.gitignore vendored
View File

@@ -49,4 +49,6 @@ test.ts
test.js test.js
/generated/prisma /generated/prisma
certificates certificates
.claude

View File

@@ -173,7 +173,14 @@
"translateInto": "Übersetzen in", "translateInto": "Übersetzen in",
"chinese": "Chinesisch", "chinese": "Chinesisch",
"english": "Englisch", "english": "Englisch",
"french": "Französisch",
"german": "Deutsch",
"italian": "Italienisch", "italian": "Italienisch",
"japanese": "Japanisch",
"korean": "Koreanisch",
"portuguese": "Portugiesisch",
"russian": "Russisch",
"spanish": "Spanisch",
"other": "Andere", "other": "Andere",
"translating": "Übersetzung läuft...", "translating": "Übersetzung läuft...",
"translate": "Übersetzen", "translate": "Übersetzen",

View File

@@ -173,7 +173,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",

View File

@@ -173,7 +173,14 @@
"translateInto": "traduire en", "translateInto": "traduire en",
"chinese": "Chinois", "chinese": "Chinois",
"english": "Anglais", "english": "Anglais",
"french": "Français",
"german": "Allemand",
"italian": "Italien", "italian": "Italien",
"japanese": "Japonais",
"korean": "Coréen",
"portuguese": "Portugais",
"russian": "Russe",
"spanish": "Espagnol",
"other": "Autre", "other": "Autre",
"translating": "traduction...", "translating": "traduction...",
"translate": "traduire", "translate": "traduire",

View File

@@ -173,7 +173,14 @@
"translateInto": "traduci in", "translateInto": "traduci in",
"chinese": "Cinese", "chinese": "Cinese",
"english": "Inglese", "english": "Inglese",
"french": "Francese",
"german": "Tedesco",
"italian": "Italiano", "italian": "Italiano",
"japanese": "Giapponese",
"korean": "Coreano",
"portuguese": "Portoghese",
"russian": "Russo",
"spanish": "Spagnolo",
"other": "Altro", "other": "Altro",
"translating": "traduzione...", "translating": "traduzione...",
"translate": "traduci", "translate": "traduci",

View File

@@ -173,7 +173,14 @@
"translateInto": "翻訳", "translateInto": "翻訳",
"chinese": "中国語", "chinese": "中国語",
"english": "英語", "english": "英語",
"french": "フランス語",
"german": "ドイツ語",
"italian": "イタリア語", "italian": "イタリア語",
"japanese": "日本語",
"korean": "韓国語",
"portuguese": "ポルトガル語",
"russian": "ロシア語",
"spanish": "スペイン語",
"other": "その他", "other": "その他",
"translating": "翻訳中...", "translating": "翻訳中...",
"translate": "翻訳", "translate": "翻訳",

View File

@@ -173,7 +173,14 @@
"translateInto": "번역", "translateInto": "번역",
"chinese": "중국어", "chinese": "중국어",
"english": "영어", "english": "영어",
"french": "프랑스어",
"german": "독일어",
"italian": "이탈리아어", "italian": "이탈리아어",
"japanese": "일본어",
"korean": "한국어",
"portuguese": "포르투갈어",
"russian": "러시아어",
"spanish": "스페인어",
"other": "기타", "other": "기타",
"translating": "번역 중...", "translating": "번역 중...",
"translate": "번역", "translate": "번역",

View File

@@ -173,7 +173,14 @@
"translateInto": "تەرجىمە قىلىش", "translateInto": "تەرجىمە قىلىش",
"chinese": "خەنزۇچە", "chinese": "خەنزۇچە",
"english": "ئىنگلىزچە", "english": "ئىنگلىزچە",
"french": "فرانسۇزچە",
"german": "گېرمانچە",
"italian": "ئىتاليانچە", "italian": "ئىتاليانچە",
"japanese": "ياپونچە",
"korean": "كورېيەچە",
"portuguese": "پورتۇگالچە",
"russian": "رۇسچە",
"spanish": "ئىسپانچە",
"other": "باشقا", "other": "باشقا",
"translating": "تەرجىمە قىلىۋاتىدۇ...", "translating": "تەرجىمە قىلىۋاتىدۇ...",
"translate": "تەرجىمە قىلىش", "translate": "تەرجىمە قىلىش",

View File

@@ -173,7 +173,14 @@
"translateInto": "翻译为", "translateInto": "翻译为",
"chinese": "中文", "chinese": "中文",
"english": "英文", "english": "英文",
"french": "法语",
"german": "德语",
"italian": "意大利语", "italian": "意大利语",
"japanese": "日语",
"korean": "韩语",
"portuguese": "葡萄牙语",
"russian": "俄语",
"spanish": "西班牙语",
"other": "其他", "other": "其他",
"translating": "翻译中...", "translating": "翻译中...",
"translate": "翻译", "translate": "翻译",

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

@@ -77,8 +77,8 @@ model Pair {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
text1 String text1 String
text2 String text2 String
language1 String @db.VarChar(20) language1 String
language2 String @db.VarChar(20) language2 String
ipa1 String? ipa1 String?
ipa2 String? ipa2 String?
folderId Int @map("folder_id") folderId Int @map("folder_id")
@@ -107,27 +107,27 @@ model Folder {
} }
model DictionaryLookUp { model DictionaryLookUp {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
userId String? @map("user_id") userId String? @map("user_id")
text String text String
queryLang String @map("query_lang") normalizedText String @default("") @map("normalized_text")
definitionLang String @map("definition_lang") queryLang String @map("query_lang")
createdAt DateTime @default(now()) @map("created_at") definitionLang String @map("definition_lang")
dictionaryWordId Int? @map("dictionary_word_id") createdAt DateTime @default(now()) @map("created_at")
dictionaryPhraseId Int? @map("dictionary_phrase_id") dictionaryItemId Int? @map("dictionary_item_id")
user User? @relation(fields: [userId], references: [id]) user User? @relation(fields: [userId], references: [id])
dictionaryWord DictionaryWord? @relation(fields: [dictionaryWordId], references: [id], onDelete: SetNull) dictionaryItem DictionaryItem? @relation(fields: [dictionaryItemId], references: [id], onDelete: SetNull)
dictionaryPhrase DictionaryPhrase? @relation(fields: [dictionaryPhraseId], references: [id], onDelete: SetNull)
@@index([userId]) @@index([userId])
@@index([createdAt]) @@index([createdAt])
@@index([text, queryLang, definitionLang]) @@index([normalizedText])
@@map("dictionary_lookups") @@map("dictionary_lookups")
} }
model DictionaryWord { model DictionaryItem {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
frequency Int @default(1)
standardForm String @map("standard_form") standardForm String @map("standard_form")
queryLang String @map("query_lang") queryLang String @map("query_lang")
definitionLang String @map("definition_lang") definitionLang String @map("definition_lang")
@@ -135,67 +135,37 @@ model DictionaryWord {
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
lookups DictionaryLookUp[] lookups DictionaryLookUp[]
entries DictionaryWordEntry[] entries DictionaryEntry[]
@@unique([standardForm, queryLang, definitionLang])
@@index([standardForm]) @@index([standardForm])
@@index([queryLang, definitionLang]) @@index([queryLang, definitionLang])
@@map("dictionary_words") @@map("dictionary_items")
} }
model DictionaryPhrase { model DictionaryEntry {
id Int @id @default(autoincrement())
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")
lookups DictionaryLookUp[]
entries DictionaryPhraseEntry[]
@@index([standardForm])
@@index([queryLang, definitionLang])
@@map("dictionary_phrases")
}
model DictionaryWordEntry {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
wordId Int @map("word_id") itemId Int @map("item_id")
ipa String ipa String?
definition String definition String
partOfSpeech String @map("part_of_speech") partOfSpeech String? @map("part_of_speech")
example String example String
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
word DictionaryWord @relation(fields: [wordId], references: [id], onDelete: Cascade) item DictionaryItem @relation(fields: [itemId], references: [id], onDelete: Cascade)
@@index([wordId]) @@index([itemId])
@@index([createdAt]) @@index([createdAt])
@@map("dictionary_word_entries") @@map("dictionary_entries")
}
model DictionaryPhraseEntry {
id Int @id @default(autoincrement())
phraseId Int @map("phrase_id")
definition String
example String
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
phrase DictionaryPhrase @relation(fields: [phraseId], references: [id], onDelete: Cascade)
@@index([phraseId])
@@index([createdAt])
@@map("dictionary_phrase_entries")
} }
model TranslationHistory { model TranslationHistory {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
userId String? @map("user_id") userId String? @map("user_id")
sourceText String @map("source_text") sourceText String @map("source_text")
sourceLanguage String @map("source_language") @db.VarChar(20) sourceLanguage String @map("source_language")
targetLanguage String @map("target_language") @db.VarChar(20) targetLanguage String @map("target_language")
translatedText String @map("translated_text") translatedText String @map("translated_text")
sourceIpa String? @map("source_ipa") sourceIpa String? @map("source_ipa")
targetIpa String? @map("target_ipa") targetIpa String? @map("target_ipa")

View File

@@ -1,75 +1,42 @@
import { DictWordEntry, DictPhraseEntry } from "./types"; import { TSharedEntry } from "@/shared";
interface DictionaryEntryProps { interface DictionaryEntryProps {
entry: DictWordEntry | DictPhraseEntry; entry: TSharedEntry;
} }
export function DictionaryEntry({ entry }: DictionaryEntryProps) { export function DictionaryEntry({ entry }: DictionaryEntryProps) {
// 检查是否有 ipa 字段来判断是否为单词条目
const isWordEntry = "ipa" in entry && "partOfSpeech" in entry;
if (isWordEntry) {
// 单词条目
const wordEntry = entry as DictWordEntry;
return (
<div>
{/* 音标和词性 */}
<div className="flex items-center gap-3 mb-3">
{wordEntry.ipa && (
<span className="text-gray-600 text-lg">
[{wordEntry.ipa}]
</span>
)}
{wordEntry.partOfSpeech && (
<span className="px-3 py-1 bg-[#35786f] text-white text-sm rounded-full">
{wordEntry.partOfSpeech}
</span>
)}
</div>
{/* 释义 */}
<div className="mb-3">
<h3 className="text-sm font-semibold text-gray-700 mb-1">
</h3>
<p className="text-gray-800">{wordEntry.definition}</p>
</div>
{/* 例句 */}
{wordEntry.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]">
{wordEntry.example}
</p>
</div>
)}
</div>
);
}
// 短语条目
const phraseEntry = entry as DictPhraseEntry;
return ( return (
<div> <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"> <div className="mb-3">
<h3 className="text-sm font-semibold text-gray-700 mb-1"> <h3 className="text-sm font-semibold text-gray-700 mb-1">
</h3> </h3>
<p className="text-gray-800">{phraseEntry.definition}</p> <p className="text-gray-800">{entry.definition}</p>
</div> </div>
{/* 例句 */} {/* 例句 */}
{phraseEntry.example && ( {entry.example && (
<div> <div>
<h3 className="text-sm font-semibold text-gray-700 mb-1"> <h3 className="text-sm font-semibold text-gray-700 mb-1">
</h3> </h3>
<p className="text-gray-700 pl-4 border-l-4 border-[#35786f]"> <p className="text-gray-700 pl-4 border-l-4 border-[#35786f]">
{phraseEntry.example} {entry.example}
</p> </p>
</div> </div>
)} )}

View File

@@ -1,141 +0,0 @@
"use client";
import { useState, useEffect } from "react";
import Container from "@/components/ui/Container";
import { lookUp } from "@/lib/server/bigmodel/dictionaryActions";
import { toast } from "sonner";
import { authClient } from "@/lib/auth-client";
import { Folder } from "../../../../generated/prisma/browser";
import { getFoldersByUserId } from "@/lib/server/services/folderService";
import { DictLookUpResponse, isDictErrorResponse } from "./types";
import { SearchForm } from "./SearchForm";
import { SearchResult } from "./SearchResult";
import { useTranslations } from "next-intl";
import { POPULAR_LANGUAGES } from "./constants";
export default function Dictionary() {
const t = useTranslations("dictionary");
const [searchQuery, setSearchQuery] = useState("");
const [searchResult, setSearchResult] = useState<DictLookUpResponse | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
const [queryLang, setQueryLang] = useState("english");
const [definitionLang, setDefinitionLang] = useState("chinese");
const [selectedFolderId, setSelectedFolderId] = useState<number | null>(null);
const [folders, setFolders] = useState<Folder[]>([]);
const { data: session } = authClient.useSession();
// 加载用户的文件夹列表
useEffect(() => {
if (session) {
getFoldersByUserId(session.user.id as string)
.then((loadedFolders) => {
setFolders(loadedFolders);
// 如果有文件夹且未选择,默认选择第一个
if (loadedFolders.length > 0 && !selectedFolderId) {
setSelectedFolderId(loadedFolders[0].id);
}
});
}
}, [session, selectedFolderId]);
// 将 code 转换为 nativeName
const getNativeName = (code: string) => {
return POPULAR_LANGUAGES.find(l => l.code === code)?.nativeName || code;
};
const handleSearch = async (e: React.FormEvent) => {
e.preventDefault();
if (!searchQuery.trim()) return;
setIsSearching(true);
setHasSearched(true);
setSearchResult(null);
try {
// 使用查询语言和释义语言的 nativeName
const result = await lookUp({
text: searchQuery,
definitionLang: getNativeName(definitionLang),
queryLang: getNativeName(queryLang),
forceRelook: false
})
// 检查是否为错误响应
if (isDictErrorResponse(result)) {
toast.error(result.error);
setSearchResult(null);
} else {
setSearchResult(result);
}
} catch (error) {
console.error("词典查询失败:", error);
toast.error(t("lookupFailed"));
setSearchResult(null);
} finally {
setIsSearching(false);
}
};
return (
<div className="min-h-[calc(100vh-64px)] bg-[#35786f]">
{/* 搜索区域 */}
<div className="flex items-center justify-center px-4 py-12">
<Container className="max-w-3xl w-full p-4">
<SearchForm
searchQuery={searchQuery}
onSearchQueryChange={setSearchQuery}
isSearching={isSearching}
onSearch={handleSearch}
queryLang={queryLang}
onQueryLangChange={setQueryLang}
definitionLang={definitionLang}
onDefinitionLangChange={setDefinitionLang}
/>
</Container>
</div>
{/* 搜索结果区域 */}
<div className="flex-1 px-4 pb-12">
<Container className="max-w-3xl w-full p-4">
{isSearching && (
<div className="text-center py-8">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-white"></div>
<p className="mt-4 text-white">{t("loading")}</p>
</div>
)}
{!isSearching && hasSearched && !searchResult && (
<div className="text-center py-12 bg-white/20 rounded-lg">
<p className="text-gray-800 text-xl">{t("noResults")}</p>
<p className="text-gray-600 mt-2">{t("tryOtherWords")}</p>
</div>
)}
{!isSearching && searchResult && !isDictErrorResponse(searchResult) && (
<SearchResult
searchResult={searchResult}
searchQuery={searchQuery}
queryLang={queryLang}
definitionLang={definitionLang}
folders={folders}
selectedFolderId={selectedFolderId}
onFolderSelect={setSelectedFolderId}
onResultUpdate={setSearchResult}
onSearchingChange={setIsSearching}
getNativeName={getNativeName}
/>
)}
{!hasSearched && (
<div className="text-center py-12 bg-white/20 rounded-lg">
<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>
)}
</Container>
</div>
</div>
);
}

View File

@@ -38,18 +38,18 @@ export function SearchForm({
</div> </div>
{/* 搜索表单 */} {/* 搜索表单 */}
<form onSubmit={onSearch} className="flex gap-2"> <form onSubmit={onSearch} className="flex flex-col sm:flex-row gap-2">
<input <input
type="text" type="text"
value={searchQuery} value={searchQuery}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => onSearchQueryChange(e.target.value)} onChange={(e: React.ChangeEvent<HTMLInputElement>) => onSearchQueryChange(e.target.value)}
placeholder={t("searchPlaceholder")} placeholder={t("searchPlaceholder")}
className="flex-1 px-4 py-3 text-lg text-gray-800 focus:outline-none border-b-2 border-gray-600 bg-white/90 rounded" className="flex-1 min-w-0 px-4 py-3 text-lg text-gray-800 focus:outline-none border-b-2 border-gray-600 bg-white/90 rounded"
/> />
<LightButton <LightButton
type="submit" type="submit"
disabled={isSearching || !searchQuery.trim()} disabled={isSearching || !searchQuery.trim()}
className="px-6 py-3" className="px-6 py-3 whitespace-nowrap text-center sm:min-w-30"
> >
{isSearching ? t("searching") : t("search")} {isSearching ? t("searching") : t("search")}
</LightButton> </LightButton>

View File

@@ -1,29 +1,22 @@
import { Plus, RefreshCw } from "lucide-react"; import { Plus, RefreshCw } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
import { Folder } from "../../../../generated/prisma/browser";
import { createPair } from "@/lib/server/services/pairService";
import { lookUp } from "@/lib/server/bigmodel/dictionaryActions";
import {
DictWordResponse,
DictPhraseResponse,
isDictWordResponse,
DictWordEntry,
isDictErrorResponse,
} from "./types";
import { DictionaryEntry } from "./DictionaryEntry"; import { DictionaryEntry } from "./DictionaryEntry";
import { POPULAR_LANGUAGES } from "./constants";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { performDictionaryLookup } from "./utils";
import { TSharedItem } from "@/shared";
import { TSharedFolder } from "@/shared/folder-type";
import { actionCreatePair } from "@/modules/folder";
interface SearchResultProps { interface SearchResultProps {
searchResult: DictWordResponse | DictPhraseResponse; searchResult: TSharedItem;
searchQuery: string; searchQuery: string;
queryLang: string; queryLang: string;
definitionLang: string; definitionLang: string;
folders: Folder[]; folders: TSharedFolder[];
selectedFolderId: number | null; selectedFolderId: number | null;
onFolderSelect: (folderId: number | null) => void; onFolderSelect: (folderId: number | null) => void;
onResultUpdate: (newResult: DictWordResponse | DictPhraseResponse) => void; onResultUpdate: (newResult: TSharedItem) => void;
onSearchingChange: (isSearching: boolean) => void; onSearchingChange: (isSearching: boolean) => void;
getNativeName: (code: string) => string; getNativeName: (code: string) => string;
} }
@@ -46,26 +39,21 @@ export function SearchResult({
const handleRelookup = async () => { const handleRelookup = async () => {
onSearchingChange(true); onSearchingChange(true);
try { const result = await performDictionaryLookup(
const result = await lookUp({ {
text: searchQuery, text: searchQuery,
definitionLang: getNativeName(definitionLang),
queryLang: getNativeName(queryLang), queryLang: getNativeName(queryLang),
definitionLang: getNativeName(definitionLang),
forceRelook: true forceRelook: true
}); },
t
);
if (isDictErrorResponse(result)) { if (result) {
toast.error(result.error); onResultUpdate(result);
} else {
onResultUpdate(result);
toast.success(t("relookupSuccess"));
}
} catch (error) {
console.error("词典重新查询失败:", error);
toast.error(t("lookupFailed"));
} finally {
onSearchingChange(false);
} }
onSearchingChange(false);
}; };
const handleSave = () => { const handleSave = () => {
@@ -79,12 +67,12 @@ export function SearchResult({
} }
const entry = searchResult.entries[0]; const entry = searchResult.entries[0];
createPair({ actionCreatePair({
text1: searchResult.standardForm, text1: searchResult.standardForm,
text2: entry.definition, text2: entry.definition,
language1: queryLang, language1: queryLang,
language2: definitionLang, language2: definitionLang,
ipa1: isDictWordResponse(searchResult) && (entry as DictWordEntry).ipa ? (entry as DictWordEntry).ipa : undefined, ipa1: entry.ipa,
folderId: selectedFolderId, folderId: selectedFolderId,
}) })
.then(() => { .then(() => {

View File

@@ -1,11 +0,0 @@
// 类型定义
export * from "./types";
// 常量
export * from "./constants";
// 组件
export { default as DictionaryPage } from "./DictionaryPage";
export { SearchForm } from "./SearchForm";
export { SearchResult } from "./SearchResult";
export { DictionaryEntry } from "./DictionaryEntry";

View File

@@ -1 +1,133 @@
export { default } from "./DictionaryPage"; "use client";
import { useState, useEffect } from "react";
import Container from "@/components/ui/Container";
import { authClient } from "@/lib/auth-client";
import { SearchForm } from "./SearchForm";
import { SearchResult } from "./SearchResult";
import { useTranslations } from "next-intl";
import { POPULAR_LANGUAGES } from "./constants";
import { performDictionaryLookup } from "./utils";
import { TSharedItem } from "@/shared";
import { actionGetFoldersByUserId } from "@/modules/folder";
import { TSharedFolder } from "@/shared/folder-type";
import { toast } from "sonner";
export default function DictionaryPage() {
const t = useTranslations("dictionary");
const [searchQuery, setSearchQuery] = useState("");
const [searchResult, setSearchResult] = useState<TSharedItem | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [hasSearched, setHasSearched] = useState(false);
const [queryLang, setQueryLang] = useState("english");
const [definitionLang, setDefinitionLang] = useState("chinese");
const [selectedFolderId, setSelectedFolderId] = useState<number | null>(null);
const [folders, setFolders] = useState<TSharedFolder[]>([]);
const { data: session } = authClient.useSession();
// 加载用户的文件夹列表
useEffect(() => {
if (session) {
actionGetFoldersByUserId(session.user.id as string)
.then(result => {
if (!result.success || !result.data) throw result.message;
return result.data;
})
.then((loadedFolders) => {
setFolders(loadedFolders);
// 如果有文件夹且未选择,默认选择第一个
if (loadedFolders.length > 0 && !selectedFolderId) {
setSelectedFolderId(loadedFolders[0].id);
}
}).catch(e => toast.error);
}
}, [session, selectedFolderId]);
// 将 code 转换为 nativeName
const getNativeName = (code: string) => {
return POPULAR_LANGUAGES.find(l => l.code === code)?.nativeName || code;
};
const handleSearch = async (e: React.FormEvent) => {
e.preventDefault();
if (!searchQuery.trim()) return;
setIsSearching(true);
setHasSearched(true);
setSearchResult(null);
const result = await performDictionaryLookup(
{
text: searchQuery,
queryLang: getNativeName(queryLang),
definitionLang: getNativeName(definitionLang),
forceRelook: false
},
t
);
setSearchResult(result);
setIsSearching(false);
};
return (
<div className="min-h-[calc(100vh-64px)] bg-[#35786f]">
{/* 搜索区域 */}
<div className="flex items-center justify-center px-4 py-12">
<Container className="max-w-3xl w-full p-4">
<SearchForm
searchQuery={searchQuery}
onSearchQueryChange={setSearchQuery}
isSearching={isSearching}
onSearch={handleSearch}
queryLang={queryLang}
onQueryLangChange={setQueryLang}
definitionLang={definitionLang}
onDefinitionLangChange={setDefinitionLang}
/>
</Container>
</div>
{/* 搜索结果区域 */}
<div className="flex-1 px-4 pb-12">
<Container className="max-w-3xl w-full p-4">
{isSearching && (
<div className="text-center py-8">
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-white"></div>
<p className="mt-4 text-white">{t("loading")}</p>
</div>
)}
{!isSearching && hasSearched && !searchResult && (
<div className="text-center py-12 bg-white/20 rounded-lg">
<p className="text-gray-800 text-xl">{t("noResults")}</p>
<p className="text-gray-600 mt-2">{t("tryOtherWords")}</p>
</div>
)}
{!isSearching && searchResult && (
<SearchResult
searchResult={searchResult}
searchQuery={searchQuery}
queryLang={queryLang}
definitionLang={definitionLang}
folders={folders}
selectedFolderId={selectedFolderId}
onFolderSelect={setSelectedFolderId}
onResultUpdate={setSearchResult}
onSearchingChange={setIsSearching}
getNativeName={getNativeName}
/>
)}
{!hasSearched && (
<div className="text-center py-12 bg-white/20 rounded-lg">
<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>
)}
</Container>
</div>
</div>
);
}

View File

@@ -1,2 +0,0 @@
// 从 shared 文件夹导出所有词典类型和类型守卫
export * from "@/lib/shared";

View File

@@ -0,0 +1,25 @@
import { toast } from "sonner";
import { actionLookUpDictionary } from "@/modules/dictionary/dictionary-action";
import { ActionInputLookUpDictionary, ActionOutputLookUpDictionary } from "@/modules/dictionary";
import { TSharedItem } from "@/shared";
export async function performDictionaryLookup(
options: ActionInputLookUpDictionary,
t?: (key: string) => string
): Promise<TSharedItem | null> {
const { text, queryLang, definitionLang, forceRelook = false, userId } = options;
const result = await actionLookUpDictionary({
text,
queryLang,
definitionLang,
forceRelook,
userId
});
if (!result.success || !result.data) return null;
if (forceRelook && t) {
toast.success(t("relookupSuccess"));
}
return result.data;
}

View File

@@ -2,10 +2,10 @@
import { useState } from "react"; import { useState } from "react";
import { useAudioPlayer } from "@/hooks/useAudioPlayer"; import { useAudioPlayer } from "@/hooks/useAudioPlayer";
import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/server/bigmodel/tts"; import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/bigmodel/tts";
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 { Pair } from "../../../../generated/prisma/browser";
const myFont = localFont({ const myFont = localFont({

View File

@@ -3,7 +3,7 @@ import { getTranslations } from "next-intl/server";
import { import {
getFoldersWithTotalPairsByUserId, getFoldersWithTotalPairsByUserId,
} from "@/lib/server/services/folderService"; } from "@/lib/server/services/folderService";
import { isNonNegativeInteger } from "@/lib/utils"; import { isNonNegativeInteger } from "@/utils/random";
import FolderSelector from "./FolderSelector"; import FolderSelector from "./FolderSelector";
import Memorize from "./Memorize"; import Memorize from "./Memorize";
import { getPairsByFolderId } from "@/lib/server/services/pairService"; import { getPairsByFolderId } from "@/lib/server/services/pairService";

View File

@@ -14,10 +14,10 @@ import SaveList from "./SaveList";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { getLocalStorageOperator } from "@/lib/browser/localStorageOperators"; import { getLocalStorageOperator } from "@/lib/browser/localStorageOperators";
import { genIPA, genLanguage } from "@/lib/server/bigmodel/translatorActions"; import { genIPA, genLanguage } from "@/modules/translator/translator-action";
import { logger } from "@/lib/logger"; import { logger } from "@/lib/logger";
import PageLayout from "@/components/ui/PageLayout"; import PageLayout from "@/components/ui/PageLayout";
import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/server/bigmodel/tts"; 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");

View File

@@ -12,14 +12,14 @@ import { useTranslations } from "next-intl";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import z from "zod"; import z from "zod";
import AddToFolder from "./AddToFolder"; import AddToFolder from "./AddToFolder";
import { translateText } from "@/lib/server/bigmodel/translatorActions"; import { translateText } from "@/modules/translator/translator-action";
import type { TranslateTextOutput } from "@/lib/server/services/types"; import type { TranslateTextOutput } from "@/lib/server/services/types";
import { toast } from "sonner"; import { toast } from "sonner";
import FolderSelector from "./FolderSelector"; import FolderSelector from "./FolderSelector";
import { createPair } from "@/lib/server/services/pairService"; import { createPair } from "@/lib/server/services/pairService";
import { shallowEqual } from "@/lib/utils"; import { shallowEqual } from "@/utils/random";
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/server/bigmodel/tts"; import { getTTSUrl, TTS_SUPPORTED_LANGUAGES } from "@/lib/bigmodel/tts";
export default function TranslatorPage() { export default function TranslatorPage() {
const t = useTranslations("translator"); const t = useTranslations("translator");

View File

@@ -2,11 +2,11 @@
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 Container from "@/components/ui/Container"; import Container from "@/components/ui/Container";
import Input from "@/components/ui/Input"; import Input from "@/components/ui/Input";
import { LightButton } from "@/components/ui/buttons"; import { LightButton } from "@/components/ui/buttons";
import { authClient } from "@/lib/auth-client"; import { authClient } from "@/lib/auth-client";
import { signInAction, signUpAction, SignUpState } from "@/modules/auth";
interface AuthFormProps { interface AuthFormProps {
redirectTo?: string; redirectTo?: string;
@@ -225,7 +225,7 @@ export default function AuthForm({ redirectTo }: AuthFormProps) {
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"
> >
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor"> <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/> <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg> </svg>
{t(mode === 'signin' ? 'signInWithGitHub' : 'signUpWithGitHub')} {t(mode === 'signin' ? 'signInWithGitHub' : 'signUpWithGitHub')}
</LightButton> </LightButton>

View File

@@ -8,23 +8,17 @@ import {
Trash2, Trash2,
} from "lucide-react"; } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { logger } from "@/lib/logger";
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 PageLayout from "@/components/ui/PageLayout";
import PageHeader from "@/components/ui/PageHeader"; import PageHeader from "@/components/ui/PageHeader";
import CardList from "@/components/ui/CardList"; import CardList from "@/components/ui/CardList";
import { actionCreateFolder, actionDeleteFolderById, actionGetFoldersWithTotalPairsByUserId, actionRenameFolderById } from "@/modules/folder";
import { TSharedFolderWithTotalPairs } from "@/shared/folder-type";
interface FolderProps { interface FolderProps {
folder: Folder & { total: number }; folder: TSharedFolderWithTotalPairs;
refresh: () => void; refresh: () => void;
} }
@@ -62,7 +56,15 @@ const FolderCard = ({ folder, refresh }: FolderProps) => {
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:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors" className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors"
@@ -74,7 +76,15 @@ const FolderCard = ({ folder, refresh }: FolderProps) => {
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="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
@@ -87,33 +97,37 @@ const FolderCard = ({ folder, refresh }: FolderProps) => {
); );
}; };
export default function FoldersClient({ userId }: { userId: string }) { export default 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) {
setLoading(false); setFolders(folders.data);
}) setLoading(false);
.catch((error) => { }
logger.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);
logger.error("更新文件夹失败", error); else await actionGetFoldersWithTotalPairsByUserId(userId)
} .then((folders) => {
if (folders.success && folders.data) {
setFolders(folders.data);
}
});
});
setLoading(false);
}; };
return ( return (
@@ -127,11 +141,14 @@ export default function FoldersClient({ userId }: { userId: string }) {
if (!folderName) return; if (!folderName) return;
setLoading(true); setLoading(true);
try { try {
await createFolder({ await actionCreateFolder(userId, folderName)
name: folderName, .then(result => {
userId: userId, if (result.success) {
}); updateFolders();
await updateFolders(); } else {
toast.error(result.message);
}
});
} finally { } finally {
setLoading(false); setLoading(false);
} }

View File

@@ -3,30 +3,20 @@
import { ArrowLeft, Plus } from "lucide-react"; import { ArrowLeft, Plus } from "lucide-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { redirect, useRouter } from "next/navigation"; import { redirect, useRouter } from "next/navigation";
import {
createPair,
deletePairById,
getPairsByFolderId,
} from "@/lib/server/services/pairService";
import AddTextPairModal from "./AddTextPairModal"; import AddTextPairModal from "./AddTextPairModal";
import TextPairCard from "./TextPairCard"; import TextPairCard from "./TextPairCard";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import PageLayout from "@/components/ui/PageLayout"; import PageLayout from "@/components/ui/PageLayout";
import { GreenButton } from "@/components/ui/buttons"; import { GreenButton } from "@/components/ui/buttons";
import { logger } from "@/lib/logger";
import { IconButton } from "@/components/ui/buttons"; import { IconButton } from "@/components/ui/buttons";
import CardList from "@/components/ui/CardList"; import CardList from "@/components/ui/CardList";
import { actionCreatePair, actionDeletePairById, actionGetPairsByFolderId } from "@/modules/folder";
import { TSharedPair } from "@/shared/folder-type";
import { toast } from "sonner";
export interface TextPair {
id: number;
text1: string;
text2: string;
language1: string;
language2: string;
}
export default function InFolder({ folderId }: { folderId: number }) { export default function InFolder({ folderId }: { folderId: number; }) {
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();
@@ -35,25 +25,26 @@ 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;
logger.error("获取文本对失败", error); }).then(setTextPairs)
} finally { .catch(toast.error)
setLoading(false); .finally(() => {
} 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;
logger.error("获取文本对失败", error); }).then(setTextPairs)
} .catch(toast.error);
}; };
return ( return (
@@ -123,8 +114,11 @@ export default function InFolder({ folderId }: { folderId: number }) {
key={textPair.id} key={textPair.id}
textPair={textPair} textPair={textPair}
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}
/> />
@@ -143,7 +137,7 @@ export default function InFolder({ folderId }: { folderId: number }) {
language1: string, language1: string,
language2: string, language2: string,
) => { ) => {
await createPair({ await actionCreatePair({
text1: text1, text1: text1,
text2: text2, text2: text2,
language1: language1, language1: language1,
@@ -155,4 +149,4 @@ export default function InFolder({ folderId }: { folderId: number }) {
/> />
</PageLayout> </PageLayout>
); );
} };

View File

@@ -1,13 +1,13 @@
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 UpdateTextPairModal from "./UpdateTextPairModal";
import { useTranslations } from "next-intl"; import { useTranslations } from "next-intl";
import { UpdatePairInput } from "@/lib/server/services/types"; import { TSharedPair } from "@/shared/folder-type";
import { actionUpdatePairById, ActionInputUpdatePairById } from "@/modules/folder";
import { toast } from "sonner";
interface TextPairCardProps { interface TextPairCardProps {
textPair: TextPair; textPair: TSharedPair;
onDel: () => void; onDel: () => void;
refreshTextPairs: () => void; refreshTextPairs: () => void;
} }
@@ -66,8 +66,8 @@ export default function TextPairCard({
<UpdateTextPairModal <UpdateTextPairModal
isOpen={openUpdateModal} isOpen={openUpdateModal}
onClose={() => setOpenUpdateModal(false)} onClose={() => setOpenUpdateModal(false)}
onUpdate={async (id: number, data: UpdatePairInput) => { 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

@@ -3,15 +3,15 @@ import Input from "@/components/ui/Input";
import { LocaleSelector } from "@/components/ui/LocaleSelector"; import { LocaleSelector } from "@/components/ui/LocaleSelector";
import { X } from "lucide-react"; import { X } from "lucide-react";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import { UpdatePairInput } from "@/lib/server/services/types";
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";
interface UpdateTextPairModalProps { interface UpdateTextPairModalProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
textPair: TextPair; textPair: TSharedPair;
onUpdate: (id: number, tp: UpdatePairInput) => void; onUpdate: (id: number, tp: ActionInputUpdatePairById) => void;
} }
export default function UpdateTextPairModal({ export default function UpdateTextPairModal({

View File

@@ -1,9 +1,9 @@
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";
export default async function FoldersPage({ export default async function FoldersPage({
params, params,
}: { }: {
@@ -17,7 +17,7 @@ export default async function FoldersPage({
redirect("/folders"); redirect("/folders");
} }
if (!session) redirect(`/auth?redirect=/folders/${folder_id}`); if (!session) redirect(`/auth?redirect=/folders/${folder_id}`);
if ((await getUserIdByFolderId(Number(folder_id))) !== session.user.id) { if ((await actionGetUserIdByFolderId(Number(folder_id))).data !== session.user.id) {
return <p>{t("unauthorized")}</p>; return <p>{t("unauthorized")}</p>;
} }
return <InFolder folderId={Number(folder_id)} />; return <InFolder folderId={Number(folder_id)} />;

View File

@@ -87,7 +87,7 @@ export default function Button({
const selectedClass = variant === "secondary" && selected ? "bg-gray-100" : ""; const selectedClass = variant === "secondary" && selected ? "bg-gray-100" : "";
// Background color for primary variant // Background color for primary variant
const backgroundColor = variant === "primary" ? COLORS.primary : undefined; const backgroundColor = variant === "primary" ? '#35786f' : undefined;
// Combine all classes // Combine all classes
const combinedClasses = ` const combinedClasses = `

View File

@@ -1,21 +1,15 @@
import { DictLookUpResponse } from "@/lib/shared"; import { ServiceOutputLookUp } from "@/modules/dictionary/dictionary-service-dto";
import { analyzeInput } from "./stage1-inputAnalysis"; import { analyzeInput } from "./stage1-inputAnalysis";
import { determineSemanticMapping } from "./stage2-semanticMapping"; import { determineSemanticMapping } from "./stage2-semanticMapping";
import { generateStandardForm } from "./stage3-standardForm"; import { generateStandardForm } from "./stage3-standardForm";
import { generateEntries } from "./stage4-entriesGeneration"; import { generateEntries } from "./stage4-entriesGeneration";
import { LookUpError } from "@/lib/errors";
/**
*
*
* LLM
*
*/
export async function executeDictionaryLookup( export async function executeDictionaryLookup(
text: string, text: string,
queryLang: string, queryLang: string,
definitionLang: string definitionLang: string
): Promise<DictLookUpResponse> { ): Promise<ServiceOutputLookUp> {
try { try {
// ========== 阶段 1输入分析 ========== // ========== 阶段 1输入分析 ==========
console.log("[阶段1] 开始输入分析..."); console.log("[阶段1] 开始输入分析...");
@@ -24,16 +18,12 @@ export async function executeDictionaryLookup(
// 代码层面验证:输入是否有效 // 代码层面验证:输入是否有效
if (!analysis.isValid) { if (!analysis.isValid) {
console.log("[阶段1] 输入无效:", analysis.reason); console.log("[阶段1] 输入无效:", analysis.reason);
return { throw analysis.reason || "无效输入";
error: analysis.reason || "无效输入",
};
} }
if (analysis.isEmpty) { if (analysis.isEmpty) {
console.log("[阶段1] 输入为空"); console.log("[阶段1] 输入为空");
return { throw "输入为空";
error: "输入为空",
};
} }
console.log("[阶段1] 输入分析完成:", analysis); console.log("[阶段1] 输入分析完成:", analysis);
@@ -65,9 +55,7 @@ export async function executeDictionaryLookup(
// 代码层面验证:标准形式不能为空 // 代码层面验证:标准形式不能为空
if (!standardFormResult.standardForm) { if (!standardFormResult.standardForm) {
console.error("[阶段3] 标准形式为空"); console.error("[阶段3] 标准形式为空");
return { throw "无法生成标准形式";
error: "无法生成标准形式",
};
} }
console.log("[阶段3] 标准形式生成完成:", standardFormResult); console.log("[阶段3] 标准形式生成完成:", standardFormResult);
@@ -86,7 +74,7 @@ export async function executeDictionaryLookup(
console.log("[阶段4] 词条生成完成:", entriesResult); console.log("[阶段4] 词条生成完成:", entriesResult);
// ========== 组装最终结果 ========== // ========== 组装最终结果 ==========
const finalResult: DictLookUpResponse = { const finalResult: ServiceOutputLookUp = {
standardForm: standardFormResult.standardForm, standardForm: standardFormResult.standardForm,
entries: entriesResult.entries, entries: entriesResult.entries,
}; };
@@ -97,10 +85,7 @@ export async function executeDictionaryLookup(
} catch (error) { } catch (error) {
console.error("[错误] 词典查询失败:", error); console.error("[错误] 词典查询失败:", error);
// 任何阶段失败都返回错误(包含 reason
const errorMessage = error instanceof Error ? error.message : "未知错误"; const errorMessage = error instanceof Error ? error.message : "未知错误";
return { throw new LookUpError(errorMessage);
error: errorMessage,
};
} }
} }

View File

@@ -1,5 +1,5 @@
import { getAnswer } from "../zhipu"; import { getAnswer } from "../zhipu";
import { parseAIGeneratedJSON } from "@/lib/utils"; import { parseAIGeneratedJSON } from "@/utils/json";
import { InputAnalysisResult } from "./types"; import { InputAnalysisResult } from "./types";
/** /**

View File

@@ -1,5 +1,5 @@
import { getAnswer } from "../zhipu"; import { getAnswer } from "../zhipu";
import { parseAIGeneratedJSON } from "@/lib/utils"; import { parseAIGeneratedJSON } from "@/utils/json";
import { SemanticMappingResult } from "./types"; import { SemanticMappingResult } from "./types";
/** /**

View File

@@ -1,5 +1,5 @@
import { getAnswer } from "../zhipu"; import { getAnswer } from "../zhipu";
import { parseAIGeneratedJSON } from "@/lib/utils"; import { parseAIGeneratedJSON } from "@/utils/json";
import { StandardFormResult } from "./types"; import { StandardFormResult } from "./types";
/** /**

View File

@@ -1,5 +1,5 @@
import { getAnswer } from "../zhipu"; import { getAnswer } from "../zhipu";
import { parseAIGeneratedJSON } from "@/lib/utils"; import { parseAIGeneratedJSON } from "@/utils/json";
import { EntriesGenerationResult } from "./types"; import { EntriesGenerationResult } from "./types";
/** /**

View File

@@ -1,62 +0,0 @@
"use client";
import {
TranslationHistoryArraySchema,
TranslationHistorySchema,
} from "@/lib/interfaces";
import z from "zod";
import { shallowEqual } from "../utils";
import { logger } from "@/lib/logger";
export const getLocalStorageOperator = <T extends z.ZodTypeAny>(
key: string,
schema: T,
) => {
return {
get: (): z.infer<T> => {
try {
if (!globalThis.localStorage) return [] as z.infer<T>;
const item = globalThis.localStorage.getItem(key);
if (!item) return [] as z.infer<T>;
const rawData = JSON.parse(item) as z.infer<T>;
const result = schema.safeParse(rawData);
if (result.success) {
return result.data;
} else {
logger.error(
"Invalid data structure in localStorage:",
result.error,
);
return [] as z.infer<T>;
}
} catch (e) {
logger.error(`Failed to parse ${key} data:`, e);
return [] as z.infer<T>;
}
},
set: (data: z.infer<T>) => {
if (!globalThis.localStorage) return;
globalThis.localStorage.setItem(key, JSON.stringify(data));
return data;
},
};
};
const MAX_HISTORY_LENGTH = 50;
export const tlso = getLocalStorageOperator<
typeof TranslationHistoryArraySchema
>("translator", TranslationHistoryArraySchema);
export const tlsoPush = (item: z.infer<typeof TranslationHistorySchema>) => {
const oldHistory = tlso.get();
if (oldHistory.some((v) => shallowEqual(v, item))) return oldHistory;
const newHistory = [...oldHistory, item].slice(-MAX_HISTORY_LENGTH);
tlso.set(newHistory);
return newHistory;
};

2
src/lib/errors.ts Normal file
View File

@@ -0,0 +1,2 @@
export class ValidateError extends Error { };
export class LookUpError extends Error { };

View File

@@ -1,56 +0,0 @@
import z from "zod";
export interface Word {
word: string;
x: number;
y: number;
}
export interface Letter {
letter: string;
letter_name_ipa: string;
letter_sound_ipa: string;
roman_letter?: string;
}
export type SupportedAlphabets =
| "japanese"
| "english"
| "esperanto"
| "uyghur";
export const TextSpeakerItemSchema = z.object({
text: z.string(),
ipa: z.string().optional(),
language: z.string(),
});
export const TextSpeakerArraySchema = z.array(TextSpeakerItemSchema);
export const WordDataSchema = z.object({
languages: z
.tuple([z.string(), z.string()])
.refine(([first, second]) => first !== second, {
message: "Languages must be different",
}),
wordPairs: z
.array(z.tuple([z.string(), z.string()]))
.min(1, "At least one word pair is required")
.refine(
(pairs) => {
return pairs.every(
([first, second]) => first.trim() !== "" && second.trim() !== "",
);
},
{
message: "Word pairs cannot contain empty strings",
},
),
});
export const TranslationHistorySchema = z.object({
text1: z.string(),
text2: z.string(),
language1: z.string(),
language2: z.string(),
});
export const TranslationHistoryArraySchema = z.array(TranslationHistorySchema);
export type WordData = z.infer<typeof WordDataSchema>;

View File

@@ -1,29 +0,0 @@
/**
* 统一的日志工具
* 在生产环境中可以通过环境变量控制日志级别
*/
type LogLevel = 'info' | 'warn' | 'error';
const isDevelopment = process.env.NODE_ENV === 'development';
export const logger = {
error: (message: string, error?: unknown) => {
if (isDevelopment) {
console.error(message, error);
}
// 在生产环境中,这里可以发送到错误追踪服务(如 Sentry
},
warn: (message: string, data?: unknown) => {
if (isDevelopment) {
console.warn(message, data);
}
},
info: (message: string, data?: unknown) => {
if (isDevelopment) {
console.info(message, data);
}
},
};

View File

@@ -1,141 +0,0 @@
"use server";
import { executeDictionaryLookup } from "./dictionary";
import { createLookUp, createPhrase, createWord, createPhraseEntry, createWordEntry, selectLastLookUp } from "../services/dictionaryService";
import { DictLookUpRequest, DictWordResponse, isDictErrorResponse, isDictPhraseResponse, isDictWordResponse, type DictLookUpResponse } from "@/lib/shared";
const saveResult = async (req: DictLookUpRequest, res: DictLookUpResponse) => {
if (isDictErrorResponse(res)) return;
else if (isDictPhraseResponse(res)) {
// 先创建 Phrase
const phrase = await createPhrase({
standardForm: res.standardForm,
queryLang: req.queryLang,
definitionLang: req.definitionLang,
});
// 创建 Lookup
await createLookUp({
userId: req.userId,
text: req.text,
queryLang: req.queryLang,
definitionLang: req.definitionLang,
dictionaryPhraseId: phrase.id,
});
// 创建 Entries
for (const entry of res.entries) {
await createPhraseEntry({
phraseId: phrase.id,
definition: entry.definition,
example: entry.example,
});
}
} else if (isDictWordResponse(res)) {
// 先创建 Word
const word = await createWord({
standardForm: (res as DictWordResponse).standardForm,
queryLang: req.queryLang,
definitionLang: req.definitionLang,
});
// 创建 Lookup
await createLookUp({
userId: req.userId,
text: req.text,
queryLang: req.queryLang,
definitionLang: req.definitionLang,
dictionaryWordId: word.id,
});
// 创建 Entries
for (const entry of (res as DictWordResponse).entries) {
await createWordEntry({
wordId: word.id,
ipa: entry.ipa,
definition: entry.definition,
partOfSpeech: entry.partOfSpeech,
example: entry.example,
});
}
}
};
/**
* 查询单词或短语
*
* 使用模块化的词典查询系统将提示词拆分为6个阶段
* - 阶段0基础系统提示
* - 阶段1输入解析与语言识别
* - 阶段2跨语言语义映射决策
* - 阶段3standardForm 生成与规范化
* - 阶段4释义与词条生成
* - 阶段5错误处理
* - 阶段6最终输出封装
*/
export const lookUp = async ({
text,
queryLang,
definitionLang,
userId,
forceRelook = false
}: DictLookUpRequest): Promise<DictLookUpResponse> => {
try {
const lastLookUp = await selectLastLookUp({
text,
queryLang,
definitionLang
});
if (forceRelook || !lastLookUp) {
// 使用新的模块化查询系统
const response = await executeDictionaryLookup(
text,
queryLang,
definitionLang
);
saveResult({
text,
queryLang,
definitionLang,
userId,
forceRelook
}, response);
return response;
} else {
// 从数据库返回缓存的结果
if (lastLookUp.dictionaryWordId) {
createLookUp({
userId: userId,
text: text,
queryLang: queryLang,
definitionLang: definitionLang,
dictionaryWordId: lastLookUp.dictionaryWordId,
});
return {
standardForm: lastLookUp.dictionaryWord!.standardForm,
entries: lastLookUp.dictionaryWord!.entries
};
} else if (lastLookUp.dictionaryPhraseId) {
createLookUp({
userId: userId,
text: text,
queryLang: queryLang,
definitionLang: definitionLang,
dictionaryPhraseId: lastLookUp.dictionaryPhraseId
});
return {
standardForm: lastLookUp.dictionaryPhrase!.standardForm,
entries: lastLookUp.dictionaryPhrase!.entries
};
} else {
return { error: "Database structure error!" };
}
}
} catch (error) {
console.log(error);
return { error: "LOOK_UP_ERROR" };
}
};

View File

@@ -1,62 +0,0 @@
"use server";
import {
CreateDictionaryLookUpInput,
DictionaryLookUpQuery,
CreateDictionaryPhraseInput,
CreateDictionaryPhraseEntryInput,
CreateDictionaryWordInput,
CreateDictionaryWordEntryInput
} from "./types";
import prisma from "../../db";
export async function selectLastLookUp(content: DictionaryLookUpQuery) {
return prisma.dictionaryLookUp.findFirst({
where: content,
include: {
dictionaryPhrase: {
include: {
entries: true
}
},
dictionaryWord: {
include: {
entries: true
}
}
},
orderBy: {
createdAt: 'desc'
}
});
}
export async function createPhraseEntry(content: CreateDictionaryPhraseEntryInput) {
return prisma.dictionaryPhraseEntry.create({
data: content
});
}
export async function createWordEntry(content: CreateDictionaryWordEntryInput) {
return prisma.dictionaryWordEntry.create({
data: content
});
}
export async function createPhrase(content: CreateDictionaryPhraseInput) {
return prisma.dictionaryPhrase.create({
data: content
});
}
export async function createWord(content: CreateDictionaryWordInput) {
return prisma.dictionaryWord.create({
data: content
});
}
export async function createLookUp(content: CreateDictionaryLookUpInput) {
return prisma.dictionaryLookUp.create({
data: content
});
}

View File

@@ -1,70 +0,0 @@
"use server";
import { CreateFolderInput, UpdateFolderInput } from "./types";
import prisma from "../../db";
export async function getFoldersByUserId(userId: string) {
return prisma.folder.findMany({
where: {
userId: userId,
},
});
}
export async function renameFolderById(id: number, newName: string) {
return prisma.folder.update({
where: {
id: id,
},
data: {
name: newName,
},
});
}
export async function getFoldersWithTotalPairsByUserId(userId: string) {
const folders = await prisma.folder.findMany({
where: { userId },
include: {
_count: {
select: { pairs: true },
},
},
});
return folders.map(folder => ({
...folder,
total: folder._count?.pairs ?? 0,
}));
}
export async function createFolder(folder: CreateFolderInput) {
return prisma.folder.create({
data: folder,
});
}
export async function deleteFolderById(id: number) {
return prisma.folder.delete({
where: {
id: id,
},
});
}
export async function updateFolderById(id: number, data: UpdateFolderInput) {
return prisma.folder.update({
where: {
id: id,
},
data: data,
});
}
export async function getUserIdByFolderId(id: number) {
const folder = await prisma.folder.findUnique({
where: {
id: id,
},
});
return folder?.userId;
}

View File

@@ -1,46 +0,0 @@
"use server";
import { CreatePairInput, UpdatePairInput } from "./types";
import prisma from "../../db";
export async function createPair(data: CreatePairInput) {
return prisma.pair.create({
data: data,
});
}
export async function deletePairById(id: number) {
return prisma.pair.delete({
where: {
id: id,
},
});
}
export async function updatePairById(
id: number,
data: UpdatePairInput,
) {
return prisma.pair.update({
where: {
id: id,
},
data: data,
});
}
export async function getPairCountByFolderId(folderId: number) {
return prisma.pair.count({
where: {
folderId: folderId,
},
});
}
export async function getPairsByFolderId(folderId: number) {
return prisma.pair.findMany({
where: {
folderId: folderId,
},
});
}

View File

@@ -1,122 +0,0 @@
/**
* Service 层的自定义业务类型
*
* 这些类型用于替换 Prisma 生成的类型,提高代码的可维护性和抽象层次
*/
// Folder 相关
export interface CreateFolderInput {
name: string;
userId: string;
}
export interface UpdateFolderInput {
name?: string;
}
// Pair 相关
export interface CreatePairInput {
text1: string;
text2: string;
language1: string;
language2: string;
ipa1?: string;
ipa2?: string;
folderId: number;
}
export interface UpdatePairInput {
text1?: string;
text2?: string;
language1?: string;
language2?: string;
ipa1?: string;
ipa2?: string;
}
// Translation 相关
export interface CreateTranslationHistoryInput {
userId?: string;
sourceText: string;
sourceLanguage: string;
targetLanguage: string;
translatedText: string;
sourceIpa?: string;
targetIpa?: string;
}
export interface TranslationHistoryQuery {
sourceText: string;
targetLanguage: string;
}
// Dictionary 相关
export interface CreateDictionaryLookUpInput {
userId?: string;
text: string;
queryLang: string;
definitionLang: string;
dictionaryWordId?: number;
dictionaryPhraseId?: number;
}
export interface DictionaryLookUpQuery {
userId?: string;
text?: string;
queryLang?: string;
definitionLang?: string;
dictionaryWordId?: number;
dictionaryPhraseId?: number;
}
export interface CreateDictionaryWordInput {
standardForm: string;
queryLang: string;
definitionLang: string;
}
export interface CreateDictionaryPhraseInput {
standardForm: string;
queryLang: string;
definitionLang: string;
}
export interface CreateDictionaryWordEntryInput {
wordId: number;
ipa: string;
definition: string;
partOfSpeech: string;
example: string;
}
export interface CreateDictionaryPhraseEntryInput {
phraseId: number;
definition: string;
example: string;
}
// 翻译相关 - 统一翻译函数
export interface TranslateTextInput {
sourceText: string;
targetLanguage: string;
forceRetranslate?: boolean; // 默认 false
needIpa?: boolean; // 默认 true
userId?: string; // 可选用户 ID
}
export interface TranslateTextOutput {
sourceText: string;
translatedText: string;
sourceLanguage: string;
targetLanguage: string;
sourceIpa: string; // 如果 needIpa=false返回空字符串
targetIpa: string; // 如果 needIpa=false返回空字符串
}
export interface TranslationLLMResponse {
translatedText: string;
sourceLanguage: string;
targetLanguage: string;
sourceIpa?: string; // 可选,根据 needIpa 决定
targetIpa?: string; // 可选,根据 needIpa 决定
}

View File

@@ -1,29 +0,0 @@
import prisma from "@/lib/db";
import { randomUUID } from "crypto";
export async function createUserIfNotExists(email: string, name?: string | null) {
const user = await prisma.user.upsert({
where: {
email: email,
},
update: {},
create: {
id: randomUUID(),
email: email,
name: name || "New User",
},
});
return user;
}
export async function getUserIdByEmail(email: string) {
const user = await prisma.user.findUnique({
where: {
email: email,
},
select: {
id: true,
},
});
return user ? user.id : null;
}

View File

@@ -1,63 +0,0 @@
export type DictLookUpRequest = {
text: string,
queryLang: string,
definitionLang: string,
userId?: string,
forceRelook: boolean;
};
export type DictWordEntry = {
ipa: string;
definition: string;
partOfSpeech: string;
example: string;
};
export type DictPhraseEntry = {
definition: string;
example: string;
};
export type DictErrorResponse = {
error: string;
};
export type DictWordResponse = {
standardForm: string;
entries: DictWordEntry[];
};
export type DictPhraseResponse = {
standardForm: string;
entries: DictPhraseEntry[];
};
export type DictLookUpResponse =
| DictErrorResponse
| DictWordResponse
| DictPhraseResponse;
// 类型守卫:判断是否为错误响应
export function isDictErrorResponse(
response: DictLookUpResponse
): response is DictErrorResponse {
return "error" in response;
}
// 类型守卫:判断是否为单词响应
export function isDictWordResponse(
response: DictLookUpResponse
): response is DictWordResponse {
if (isDictErrorResponse(response)) return false;
const entries = (response as DictWordResponse | DictPhraseResponse).entries;
return entries.length > 0 && "ipa" in entries[0] && "partOfSpeech" in entries[0];
}
// 类型守卫:判断是否为短语响应
export function isDictPhraseResponse(
response: DictLookUpResponse
): response is DictPhraseResponse {
if (isDictErrorResponse(response)) return false;
const entries = (response as DictWordResponse | DictPhraseResponse).entries;
return entries.length > 0 && !("ipa" in entries[0] || "partOfSpeech" in entries[0]);
}

View File

@@ -1 +0,0 @@
export * from "./dictionaryTypes";

View File

@@ -1,14 +0,0 @@
/**
* 主题配色常量
* 集中管理应用的品牌颜色
*
* 注意Tailwind CSS 已有的标准颜色gray、red 等)请直接使用 Tailwind 类名
* 这里只定义项目独有的品牌色
*/
export const COLORS = {
// ===== 主色调 =====
/** 主绿色 - 应用主题色,用于页面背景、主要按钮 */
primary: '#35786f',
/** 悬停绿色 - 按钮悬停状态 */
primaryHover: '#2d5f58'
} as const;

View File

@@ -67,6 +67,9 @@ export async function signUpAction(prevState: SignUpState, formData: FormData) {
redirect(redirectTo || "/"); redirect(redirectTo || "/");
} catch (error) { } catch (error) {
if (error instanceof Error && error.message.includes('NEXT_REDIRECT')) {
throw error;
}
return { return {
success: false, success: false,
message: "注册失败,请稍后再试" message: "注册失败,请稍后再试"

View File

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

View File

@@ -0,0 +1,22 @@
import { TSharedItem } from "@/shared";
import { LENGTH_MAX_DICTIONARY_TEXT, LENGTH_MAX_LANGUAGE, LENGTH_MIN_DICTIONARY_TEXT, LENGTH_MIN_LANGUAGE } from "@/shared/constant";
import { generateValidator } from "@/utils/validate";
import z from "zod";
const schemaActionInputLookUpDictionary = z.object({
text: z.string().min(LENGTH_MIN_DICTIONARY_TEXT).max(LENGTH_MAX_DICTIONARY_TEXT),
queryLang: z.string().min(LENGTH_MIN_LANGUAGE).max(LENGTH_MAX_LANGUAGE),
forceRelook: z.boolean(),
definitionLang: z.string().min(LENGTH_MIN_LANGUAGE).max(LENGTH_MAX_LANGUAGE),
userId: z.string().optional()
});
export type ActionInputLookUpDictionary = z.infer<typeof schemaActionInputLookUpDictionary>;
export const validateActionInputLookUpDictionary = generateValidator(schemaActionInputLookUpDictionary);
export type ActionOutputLookUpDictionary = {
message: string,
success: boolean;
data?: TSharedItem;
};

View File

@@ -0,0 +1,27 @@
"use server";
import { ActionInputLookUpDictionary, ActionOutputLookUpDictionary, validateActionInputLookUpDictionary } from "./dictionary-action-dto";
import { ValidateError } from "@/lib/errors";
import { serviceLookUp } from "./dictionary-service";
export const actionLookUpDictionary = async (dto: ActionInputLookUpDictionary): Promise<ActionOutputLookUpDictionary> => {
try {
return {
message: 'success',
success: true,
data: await serviceLookUp(validateActionInputLookUpDictionary(dto))
};
} catch (e) {
if (e instanceof ValidateError) {
return {
success: false,
message: e.message
};
}
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
};

View File

@@ -0,0 +1,38 @@
import { TSharedItem } from "@/shared";
export type RepoInputCreateDictionaryLookUp = {
userId?: string;
text: string;
queryLang: string;
definitionLang: string;
dictionaryItemId?: number;
};
export type RepoOutputSelectLastLookUpResult = TSharedItem & {id: number} | null;
export type RepoInputCreateDictionaryItem = {
standardForm: string;
queryLang: string;
definitionLang: string;
};
export type RepoInputCreateDictionaryEntry = {
itemId: number;
ipa?: string;
definition: string;
partOfSpeech?: string;
example: string;
};
export type RepoInputCreateDictionaryEntryWithoutItemId = {
ipa?: string;
definition: string;
partOfSpeech?: string;
example: string;
};
export type RepoInputSelectLastLookUpResult = {
text: string,
queryLang: string,
definitionLang: string;
};

View File

@@ -0,0 +1,86 @@
import { stringNormalize } from "@/utils/string";
import {
RepoInputCreateDictionaryEntry,
RepoInputCreateDictionaryEntryWithoutItemId,
RepoInputCreateDictionaryItem,
RepoInputCreateDictionaryLookUp,
RepoInputSelectLastLookUpResult,
RepoOutputSelectLastLookUpResult,
} from "./dictionary-repository-dto";
import prisma from "@/lib/db";
export async function repoSelectLastLookUpResult(dto: RepoInputSelectLastLookUpResult): Promise<RepoOutputSelectLastLookUpResult> {
const result = await prisma.dictionaryLookUp.findFirst({
where: {
normalizedText: stringNormalize(dto.text),
queryLang: dto.queryLang,
definitionLang: dto.definitionLang,
dictionaryItemId: {
not: null
}
},
include: {
dictionaryItem: {
include: {
entries: true
}
}
},
orderBy: {
createdAt: 'desc'
}
});
if (result && result.dictionaryItem) {
const item = result.dictionaryItem;
return {
id: item.id,
standardForm: item.standardForm,
entries: item.entries.filter(v => !!v).map(v => {
return {
ipa: v.ipa || undefined,
definition: v.definition,
partOfSpeech: v.partOfSpeech || undefined,
example: v.example
};
})
};
}
return null;
}
export async function repoCreateLookUp(content: RepoInputCreateDictionaryLookUp) {
return (await prisma.dictionaryLookUp.create({
data: { ...content, normalizedText: stringNormalize(content.text) }
})).id;
}
export async function repoCreateLookUpWithItemAndEntries(
itemData: RepoInputCreateDictionaryItem,
lookUpData: RepoInputCreateDictionaryLookUp,
entries: RepoInputCreateDictionaryEntryWithoutItemId[]
) {
return await prisma.$transaction(async (tx) => {
const item = await tx.dictionaryItem.create({
data: itemData
});
await tx.dictionaryLookUp.create({
data: {
...lookUpData,
normalizedText: stringNormalize(lookUpData.text),
dictionaryItemId: item.id
}
});
for (const entry of entries) {
await tx.dictionaryEntry.create({
data: {
...entry,
itemId: item.id
}
});
}
return item.id;
});
}

View File

@@ -0,0 +1,11 @@
import { TSharedItem } from "@/shared";
export type ServiceInputLookUp = {
text: string,
queryLang: string,
definitionLang: string,
forceRelook: boolean,
userId?: string;
};
export type ServiceOutputLookUp = TSharedItem;

View File

@@ -0,0 +1,61 @@
import { executeDictionaryLookup } from "@/lib/bigmodel/dictionary";
import { repoCreateLookUp, repoCreateLookUpWithItemAndEntries, repoSelectLastLookUpResult } from "./dictionary-repository";
import { ServiceInputLookUp } from "./dictionary-service-dto";
export const serviceLookUp = async (dto: ServiceInputLookUp) => {
const {
text,
queryLang,
userId,
definitionLang,
forceRelook
} = dto;
const lastLookUpResult = await repoSelectLastLookUpResult({
text,
queryLang,
definitionLang,
});
if (forceRelook || !lastLookUpResult) {
const response = await executeDictionaryLookup(
text,
queryLang,
definitionLang
);
// 使用事务确保数据一致性
repoCreateLookUpWithItemAndEntries(
{
standardForm: response.standardForm,
queryLang,
definitionLang
},
{
userId,
text,
queryLang,
definitionLang,
},
response.entries
).catch(error => {
console.error('Failed to save dictionary data:', error);
});
return response;
} else {
repoCreateLookUp({
userId: userId,
text: text,
queryLang: queryLang,
definitionLang: definitionLang,
dictionaryItemId: lastLookUpResult.id
}).catch(error => {
console.error('Failed to save dictionary data:', error);
});
return {
standardForm: lastLookUpResult.standardForm,
entries: lastLookUpResult.entries
};
}
};

View File

@@ -0,0 +1,2 @@
export * from "./dictionary-action";
export * from "./dictionary-action-dto";

View File

@@ -0,0 +1,202 @@
"use server";
import { ValidateError } from "@/lib/errors";
import { ActionInputCreatePair, ActionInputUpdatePairById, ActionOutputGetFoldersWithTotalPairsByUserId, validateActionInputCreatePair, validateActionInputUpdatePairById } from "./folder-action-dto";
import { repoCreateFolder, repoCreatePair, repoDeleteFolderById, repoDeletePairById, repoGetFoldersByUserId, repoGetFoldersWithTotalPairsByUserId, repoGetPairsByFolderId, repoGetUserIdByFolderId, repoRenameFolderById, repoUpdatePairById } from "./folder-repository";
import { validate } from "@/utils/validate";
import z from "zod";
import { LENGTH_MAX_FOLDER_NAME, LENGTH_MIN_FOLDER_NAME } from "@/shared/constant";
export async function actionGetPairsByFolderId(folderId: number) {
try {
return {
success: true,
message: 'success',
data: await repoGetPairsByFolderId(folderId)
};
} catch (e) {
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionUpdatePairById(id: number, dto: ActionInputUpdatePairById) {
try {
const validatedDto = validateActionInputUpdatePairById(dto);
await repoUpdatePairById(id, validatedDto);
return {
success: true,
message: 'success',
};
} catch (e) {
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionGetUserIdByFolderId(folderId: number) {
try {
return {
success: true,
message: 'success',
data: await repoGetUserIdByFolderId(folderId)
};
} catch (e) {
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionDeleteFolderById(folderId: number) {
try {
await repoDeleteFolderById(folderId);
return {
success: true,
message: 'success',
};
} catch (e) {
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionDeletePairById(id: number) {
try {
await repoDeletePairById(id);
return {
success: true,
message: 'success'
};
} catch (e) {
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionGetFoldersWithTotalPairsByUserId(id: string): Promise<ActionOutputGetFoldersWithTotalPairsByUserId> {
try {
return {
success: true,
message: 'success',
data: await repoGetFoldersWithTotalPairsByUserId(id)
};
} catch (e) {
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionGetFoldersByUserId(userId: string) {
try {
return {
success: true,
message: 'success',
data: await repoGetFoldersByUserId(userId)
};
} catch (e) {
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionCreatePair(dto: ActionInputCreatePair) {
try {
const validatedDto = validateActionInputCreatePair(dto);
await repoCreatePair(validatedDto);
return {
success: true,
message: 'success'
};
} catch (e) {
if (e instanceof ValidateError) {
return {
success: false,
message: e.message
};
}
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionCreateFolder(userId: string, folderName: string) {
try {
const validatedFolderName = validate(folderName,
z.string()
.trim()
.min(LENGTH_MIN_FOLDER_NAME)
.max(LENGTH_MAX_FOLDER_NAME));
await repoCreateFolder({
name: validatedFolderName,
userId: userId
});
return {
success: true,
message: 'success'
};
} catch (e) {
if (e instanceof ValidateError) {
return {
success: false,
message: e.message
};
}
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}
export async function actionRenameFolderById(id: number, newName: string) {
try {
const validatedNewName = validate(
newName,
z.string()
.min(LENGTH_MIN_FOLDER_NAME)
.max(LENGTH_MAX_FOLDER_NAME)
.trim());
await repoRenameFolderById(id, validatedNewName);
return {
success: true,
message: 'success'
};
} catch (e) {
if (e instanceof ValidateError) {
return {
success: false,
message: e.message
};
}
console.log(e);
return {
success: false,
message: 'Unknown error occured.'
};
}
}

View File

@@ -0,0 +1,34 @@
import { LENGTH_MAX_FOLDER_NAME, LENGTH_MAX_IPA, LENGTH_MAX_LANGUAGE, LENGTH_MAX_PAIR_TEXT, LENGTH_MIN_FOLDER_NAME, LENGTH_MIN_IPA, LENGTH_MIN_LANGUAGE, LENGTH_MIN_PAIR_TEXT } from "@/shared/constant";
import { TSharedFolderWithTotalPairs } from "@/shared/folder-type";
import { generateValidator } from "@/utils/validate";
import z from "zod";
export const schemaActionInputCreatePair = z.object({
text1: z.string().min(LENGTH_MIN_PAIR_TEXT).max(LENGTH_MAX_PAIR_TEXT),
text2: z.string().min(LENGTH_MIN_PAIR_TEXT).max(LENGTH_MAX_PAIR_TEXT),
language1: z.string().min(LENGTH_MIN_LANGUAGE).max(LENGTH_MAX_LANGUAGE),
language2: z.string().min(LENGTH_MIN_LANGUAGE).max(LENGTH_MAX_LANGUAGE),
ipa1: z.string().min(LENGTH_MIN_IPA).max(LENGTH_MAX_IPA).optional(),
ipa2: z.string().min(LENGTH_MIN_IPA).max(LENGTH_MAX_IPA).optional(),
folderId: z.int()
});
export type ActionInputCreatePair = z.infer<typeof schemaActionInputCreatePair>;
export const validateActionInputCreatePair = generateValidator(schemaActionInputCreatePair);
export const schemaActionInputUpdatePairById = z.object({
text1: z.string().min(LENGTH_MIN_PAIR_TEXT).max(LENGTH_MAX_PAIR_TEXT).optional(),
text2: z.string().min(LENGTH_MIN_PAIR_TEXT).max(LENGTH_MAX_PAIR_TEXT).optional(),
language1: z.string().min(LENGTH_MIN_LANGUAGE).max(LENGTH_MAX_LANGUAGE).optional(),
language2: z.string().min(LENGTH_MIN_LANGUAGE).max(LENGTH_MAX_LANGUAGE).optional(),
ipa1: z.string().min(LENGTH_MIN_IPA).max(LENGTH_MAX_IPA).optional(),
ipa2: z.string().min(LENGTH_MIN_IPA).max(LENGTH_MAX_IPA).optional(),
folderId: z.int().optional()
});
export type ActionInputUpdatePairById = z.infer<typeof schemaActionInputUpdatePairById>;
export const validateActionInputUpdatePairById = generateValidator(schemaActionInputUpdatePairById);
export type ActionOutputGetFoldersWithTotalPairsByUserId = {
message: string,
success: boolean,
data?: TSharedFolderWithTotalPairs[];
};

View File

@@ -0,0 +1,23 @@
export interface RepoInputCreateFolder {
name: string;
userId: string;
}
export interface RepoInputCreatePair {
text1: string;
text2: string;
language1: string;
language2: string;
ipa1?: string;
ipa2?: string;
folderId: number;
}
export interface RepoInputUpdatePair {
text1?: string;
text2?: string;
language1?: string;
language2?: string;
ipa1?: string;
ipa2?: string;
}

View File

@@ -0,0 +1,120 @@
import prisma from "@/lib/db";
import { RepoInputCreateFolder, RepoInputCreatePair, RepoInputUpdatePair } from "./folder-repository-dto";
export async function repoCreatePair(data: RepoInputCreatePair) {
return (await prisma.pair.create({
data: data,
})).id;
}
export async function repoDeletePairById(id: number) {
await prisma.pair.delete({
where: {
id: id,
},
});
}
export async function repoUpdatePairById(
id: number,
data: RepoInputUpdatePair,
) {
await prisma.pair.update({
where: {
id: id,
},
data: data,
});
}
export async function repoGetPairCountByFolderId(folderId: number) {
return prisma.pair.count({
where: {
folderId: folderId,
},
});
}
export async function repoGetPairsByFolderId(folderId: number) {
return (await prisma.pair.findMany({
where: {
folderId: folderId,
},
})).map(pair => {
return {
text1:pair.text1,
text2: pair.text2,
language1: pair.language1,
language2: pair.language2,
ipa1: pair.ipa1,
ipa2: pair.ipa2,
id: pair.id,
folderId: pair.folderId
}
});
}
export async function repoGetFoldersByUserId(userId: string) {
return (await prisma.folder.findMany({
where: {
userId: userId,
},
}))?.map(v => {
return {
id: v.id,
name: v.name,
userId: v.userId
};
});
}
export async function repoRenameFolderById(id: number, newName: string) {
await prisma.folder.update({
where: {
id: id,
},
data: {
name: newName,
},
});
}
export async function repoGetFoldersWithTotalPairsByUserId(userId: string) {
const folders = await prisma.folder.findMany({
where: { userId },
include: {
_count: {
select: { pairs: true },
},
},
});
return folders.map(folder => ({
id: folder.id,
name: folder.name,
userId: folder.userId,
total: folder._count?.pairs ?? 0,
}));
}
export async function repoCreateFolder(folder: RepoInputCreateFolder) {
await prisma.folder.create({
data: folder,
});
}
export async function repoDeleteFolderById(id: number) {
await prisma.folder.delete({
where: {
id: id,
},
});
}
export async function repoGetUserIdByFolderId(id: number) {
const folder = await prisma.folder.findUnique({
where: {
id: id,
},
});
return folder?.userId;
}

View File

View File

View File

@@ -0,0 +1,2 @@
export * from './folder-aciton';
export * from './folder-action-dto';

View File

@@ -1,8 +1,8 @@
"use server"; "use server";
import { getAnswer } from "./zhipu"; import { getAnswer } from "@/lib/bigmodel/zhipu";
import { selectLatestTranslation, createTranslationHistory } from "../services/translatorService"; import { selectLatestTranslation, createTranslationHistory } from "./translator-service";
import { TranslateTextInput, TranslateTextOutput, TranslationLLMResponse } from "../services/types"; import { TranslateTextInput, TranslateTextOutput, TranslationLLMResponse } from "./translator-dto";
/** /**
* @deprecated 使 translateText * @deprecated 使 translateText

View File

@@ -0,0 +1,39 @@
export interface CreateTranslationHistoryInput {
userId?: string;
sourceText: string;
sourceLanguage: string;
targetLanguage: string;
translatedText: string;
sourceIpa?: string;
targetIpa?: string;
}
export interface TranslationHistoryQuery {
sourceText: string;
targetLanguage: string;
}
export interface TranslateTextInput {
sourceText: string;
targetLanguage: string;
forceRetranslate?: boolean; // 默认 false
needIpa?: boolean; // 默认 true
userId?: string; // 可选用户 ID
}
export interface TranslateTextOutput {
sourceText: string;
translatedText: string;
sourceLanguage: string;
targetLanguage: string;
sourceIpa: string; // 如果 needIpa=false返回空字符串
targetIpa: string; // 如果 needIpa=false返回空字符串
}
export interface TranslationLLMResponse {
translatedText: string;
sourceLanguage: string;
targetLanguage: string;
sourceIpa?: string; // 可选,根据 needIpa 决定
targetIpa?: string; // 可选,根据 needIpa 决定
}

View File

@@ -1,7 +1,7 @@
"use server"; "use server";
import { CreateTranslationHistoryInput, TranslationHistoryQuery } from "./types"; import { CreateTranslationHistoryInput, TranslationHistoryQuery } from "./translator-dto";
import prisma from "../../db"; import prisma from "@/lib/db";
/** /**
* *

14
src/shared/constant.ts Normal file
View File

@@ -0,0 +1,14 @@
export const LENGTH_MAX_DICTIONARY_TEXT = 30;
export const LENGTH_MIN_DICTIONARY_TEXT = 1;
export const LENGTH_MAX_LANGUAGE = 20;
export const LENGTH_MIN_LANGUAGE = 1;
export const LENGTH_MAX_PAIR_TEXT = 50;
export const LENGTH_MIN_PAIR_TEXT = 1;
export const LENGTH_MAX_IPA = 150;
export const LENGTH_MIN_IPA = 1;
export const LENGTH_MAX_FOLDER_NAME = 20;
export const LENGTH_MIN_FOLDER_NAME = 1;

View File

@@ -0,0 +1,11 @@
export type TSharedEntry = {
definition: string,
example: string,
partOfSpeech?: string;
ipa?: string;
};
export type TSharedItem = {
standardForm: string,
entries: TSharedEntry[];
};

23
src/shared/folder-type.ts Normal file
View File

@@ -0,0 +1,23 @@
export type TSharedFolder = {
id: number,
name: string,
userId: string;
};
export type TSharedFolderWithTotalPairs = {
id: number,
name: string,
userId: string,
total: number;
};
export type TSharedPair = {
text1: string;
text2: string;
language1: string;
language2: string;
ipa1: string | null;
ipa2: string | null;
id: number;
folderId: number;
};

1
src/shared/index.ts Normal file
View File

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

25
src/utils/json.ts Normal file
View File

@@ -0,0 +1,25 @@
export function parseAIGeneratedJSON<T>(aiResponse: string): T {
// 匹配 ```json ... ``` 包裹的内容
const jsonMatch = aiResponse.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonMatch && jsonMatch[1]) {
try {
return JSON.parse(jsonMatch[1].trim());
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to parse JSON: ${error.message}`);
} else if (typeof error === 'string') {
throw new Error(`Failed to parse JSON: ${error}`);
} else {
throw new Error('Failed to parse JSON: Unknown error');
}
}
}
// 如果没有找到json代码块尝试直接解析整个字符串
try {
return JSON.parse(aiResponse.trim());
} catch (error) {
throw new Error('No valid JSON found in the response');
}
}

View File

@@ -1,3 +1,4 @@
export function isNonNegativeInteger(str: string): boolean { export function isNonNegativeInteger(str: string): boolean {
return /^\d+$/.test(str); return /^\d+$/.test(str);
} }
@@ -5,19 +6,19 @@ export function isNonNegativeInteger(str: string): boolean {
export function shallowEqual<T extends object>(obj1: T, obj2: T): boolean { export function shallowEqual<T extends object>(obj1: T, obj2: T): boolean {
const keys1 = Object.keys(obj1) as Array<keyof T>; const keys1 = Object.keys(obj1) as Array<keyof T>;
const keys2 = Object.keys(obj2) as Array<keyof T>; const keys2 = Object.keys(obj2) as Array<keyof T>;
// 首先检查键的数量是否相同 // 首先检查键的数量是否相同
if (keys1.length !== keys2.length) { if (keys1.length !== keys2.length) {
return false; return false;
} }
// 然后逐个比较键值对 // 然后逐个比较键值对
for (const key of keys1) { for (const key of keys1) {
if (obj1[key] !== obj2[key]) { if (obj1[key] !== obj2[key]) {
return false; return false;
} }
} }
return true; return true;
} }
export class SeededRandom { export class SeededRandom {
@@ -147,29 +148,3 @@ export class SeededRandom {
return shuffled; return shuffled;
} }
} }
export function parseAIGeneratedJSON<T>(aiResponse: string): T {
// 匹配 ```json ... ``` 包裹的内容
const jsonMatch = aiResponse.match(/```json\s*([\s\S]*?)\s*```/);
if (jsonMatch && jsonMatch[1]) {
try {
return JSON.parse(jsonMatch[1].trim());
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to parse JSON: ${error.message}`);
} else if (typeof error === 'string') {
throw new Error(`Failed to parse JSON: ${error}`);
} else {
throw new Error('Failed to parse JSON: Unknown error');
}
}
}
// 如果没有找到json代码块尝试直接解析整个字符串
try {
return JSON.parse(aiResponse.trim());
} catch (error) {
throw new Error('No valid JSON found in the response');
}
}

1
src/utils/string.ts Normal file
View File

@@ -0,0 +1 @@
export const stringNormalize = (s: string) => s.trim().toLowerCase();

13
src/utils/validate.ts Normal file
View File

@@ -0,0 +1,13 @@
import { ValidateError } from "@/lib/errors";
import z from "zod";
export const validate = <T, U extends z.ZodType>(dto: T, schema: U) => {
const result = schema.safeParse(dto);
if (result.success) return result.data as z.infer<U>;
const errorMessages = result.error.issues.map((issue) =>
`${issue.path.join('.')}: ${issue.message}`
).join('; ');
throw new ValidateError(`Validation failed: ${errorMessages}`);
};
export const generateValidator = <T extends z.ZodType>(schema: T) => <T>(dto: T) => validate(dto, schema);