Compare commits
7 Commits
main
...
d4d5a53747
| Author | SHA1 | Date | |
|---|---|---|---|
| d4d5a53747 | |||
| ec265be26b | |||
| 804baa64b2 | |||
| a1e42127e6 | |||
| f1d706e20c | |||
| c7cdf40f2f | |||
| a55e763525 |
@@ -35,3 +35,5 @@ build.sh
|
|||||||
|
|
||||||
# prisma
|
# prisma
|
||||||
/generated/prisma
|
/generated/prisma
|
||||||
|
|
||||||
|
.claude
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -50,3 +50,5 @@ test.js
|
|||||||
/generated/prisma
|
/generated/prisma
|
||||||
|
|
||||||
certificates
|
certificates
|
||||||
|
|
||||||
|
.claude
|
||||||
|
|||||||
@@ -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",
|
||||||
|
|||||||
@@ -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",
|
||||||
|
|||||||
@@ -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",
|
||||||
|
|||||||
@@ -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",
|
||||||
|
|||||||
@@ -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": "翻訳",
|
||||||
|
|||||||
@@ -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": "번역",
|
||||||
|
|||||||
@@ -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": "تەرجىمە قىلىش",
|
||||||
|
|||||||
@@ -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": "翻译",
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -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;
|
||||||
@@ -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")
|
||||||
@@ -110,24 +110,24 @@ 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
|
||||||
|
normalizedText String @default("") @map("normalized_text")
|
||||||
queryLang String @map("query_lang")
|
queryLang String @map("query_lang")
|
||||||
definitionLang String @map("definition_lang")
|
definitionLang String @map("definition_lang")
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
dictionaryWordId Int? @map("dictionary_word_id")
|
dictionaryItemId Int? @map("dictionary_item_id")
|
||||||
dictionaryPhraseId Int? @map("dictionary_phrase_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())
|
id Int @id @default(autoincrement())
|
||||||
standardForm String @map("standard_form")
|
itemId Int @map("item_id")
|
||||||
queryLang String @map("query_lang")
|
ipa String?
|
||||||
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())
|
|
||||||
wordId Int @map("word_id")
|
|
||||||
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")
|
||||||
|
|||||||
@@ -1,28 +1,22 @@
|
|||||||
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 (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{/* 音标和词性 */}
|
{/* 音标和词性 */}
|
||||||
<div className="flex items-center gap-3 mb-3">
|
<div className="flex items-center gap-3 mb-3">
|
||||||
{wordEntry.ipa && (
|
{entry.ipa && (
|
||||||
<span className="text-gray-600 text-lg">
|
<span className="text-gray-600 text-lg">
|
||||||
[{wordEntry.ipa}]
|
[{entry.ipa}]
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
{wordEntry.partOfSpeech && (
|
{entry.partOfSpeech && (
|
||||||
<span className="px-3 py-1 bg-[#35786f] text-white text-sm rounded-full">
|
<span className="px-3 py-1 bg-[#35786f] text-white text-sm rounded-full">
|
||||||
{wordEntry.partOfSpeech}
|
{entry.partOfSpeech}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -32,44 +26,17 @@ export function DictionaryEntry({ entry }: DictionaryEntryProps) {
|
|||||||
<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">{wordEntry.definition}</p>
|
<p className="text-gray-800">{entry.definition}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 例句 */}
|
{/* 例句 */}
|
||||||
{wordEntry.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]">
|
||||||
{wordEntry.example}
|
{entry.example}
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 短语条目
|
|
||||||
const phraseEntry = entry as DictPhraseEntry;
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
{/* 释义 */}
|
|
||||||
<div className="mb-3">
|
|
||||||
<h3 className="text-sm font-semibold text-gray-700 mb-1">
|
|
||||||
释义
|
|
||||||
</h3>
|
|
||||||
<p className="text-gray-800">{phraseEntry.definition}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 例句 */}
|
|
||||||
{phraseEntry.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]">
|
|
||||||
{phraseEntry.example}
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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>
|
||||||
|
|||||||
@@ -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);
|
|
||||||
} else {
|
|
||||||
onResultUpdate(result);
|
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(() => {
|
||||||
|
|||||||
@@ -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";
|
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
// 从 shared 文件夹导出所有词典类型和类型守卫
|
|
||||||
export * from "@/lib/shared";
|
|
||||||
25
src/app/(features)/dictionary/utils.ts
Normal file
25
src/app/(features)/dictionary/utils.ts
Normal 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;
|
||||||
|
}
|
||||||
@@ -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({
|
||||||
|
|||||||
@@ -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";
|
||||||
|
|||||||
@@ -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");
|
||||||
|
|||||||
@@ -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");
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
setFolders(folders.data);
|
||||||
setLoading(false);
|
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();
|
||||||
|
} else {
|
||||||
|
toast.error(result.message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
await updateFolders();
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
.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;
|
||||||
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>
|
||||||
);
|
);
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -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();
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -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({
|
||||||
|
|||||||
@@ -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)} />;
|
||||||
|
|||||||
@@ -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 = `
|
||||||
|
|||||||
@@ -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,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -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";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -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";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -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";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -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
2
src/lib/errors.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export class ValidateError extends Error { };
|
||||||
|
export class LookUpError extends Error { };
|
||||||
@@ -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>;
|
|
||||||
@@ -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);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
@@ -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:跨语言语义映射决策
|
|
||||||
* - 阶段3:standardForm 生成与规范化
|
|
||||||
* - 阶段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" };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -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,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -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 决定
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -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]);
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export * from "./dictionaryTypes";
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
/**
|
|
||||||
* 主题配色常量
|
|
||||||
* 集中管理应用的品牌颜色
|
|
||||||
*
|
|
||||||
* 注意:Tailwind CSS 已有的标准颜色(gray、red 等)请直接使用 Tailwind 类名
|
|
||||||
* 这里只定义项目独有的品牌色
|
|
||||||
*/
|
|
||||||
export const COLORS = {
|
|
||||||
// ===== 主色调 =====
|
|
||||||
/** 主绿色 - 应用主题色,用于页面背景、主要按钮 */
|
|
||||||
primary: '#35786f',
|
|
||||||
/** 悬停绿色 - 按钮悬停状态 */
|
|
||||||
primaryHover: '#2d5f58'
|
|
||||||
} as const;
|
|
||||||
@@ -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: "注册失败,请稍后再试"
|
||||||
1
src/modules/auth/index.ts
Normal file
1
src/modules/auth/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './auth-action';
|
||||||
22
src/modules/dictionary/dictionary-action-dto.ts
Normal file
22
src/modules/dictionary/dictionary-action-dto.ts
Normal 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;
|
||||||
|
};
|
||||||
27
src/modules/dictionary/dictionary-action.ts
Normal file
27
src/modules/dictionary/dictionary-action.ts
Normal 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.'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
38
src/modules/dictionary/dictionary-repository-dto.ts
Normal file
38
src/modules/dictionary/dictionary-repository-dto.ts
Normal 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;
|
||||||
|
};
|
||||||
86
src/modules/dictionary/dictionary-repository.ts
Normal file
86
src/modules/dictionary/dictionary-repository.ts
Normal 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;
|
||||||
|
});
|
||||||
|
}
|
||||||
11
src/modules/dictionary/dictionary-service-dto.ts
Normal file
11
src/modules/dictionary/dictionary-service-dto.ts
Normal 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;
|
||||||
61
src/modules/dictionary/dictionary-service.ts
Normal file
61
src/modules/dictionary/dictionary-service.ts
Normal 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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
2
src/modules/dictionary/index.ts
Normal file
2
src/modules/dictionary/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./dictionary-action";
|
||||||
|
export * from "./dictionary-action-dto";
|
||||||
202
src/modules/folder/folder-aciton.ts
Normal file
202
src/modules/folder/folder-aciton.ts
Normal 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.'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
34
src/modules/folder/folder-action-dto.ts
Normal file
34
src/modules/folder/folder-action-dto.ts
Normal 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[];
|
||||||
|
};
|
||||||
23
src/modules/folder/folder-repository-dto.ts
Normal file
23
src/modules/folder/folder-repository-dto.ts
Normal 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;
|
||||||
|
}
|
||||||
120
src/modules/folder/folder-repository.ts
Normal file
120
src/modules/folder/folder-repository.ts
Normal 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;
|
||||||
|
}
|
||||||
0
src/modules/folder/folder-service-dto.ts
Normal file
0
src/modules/folder/folder-service-dto.ts
Normal file
0
src/modules/folder/folder-service.ts
Normal file
0
src/modules/folder/folder-service.ts
Normal file
2
src/modules/folder/index.ts
Normal file
2
src/modules/folder/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './folder-aciton';
|
||||||
|
export * from './folder-action-dto';
|
||||||
0
src/modules/translator/translator-action-dto.ts
Normal file
0
src/modules/translator/translator-action-dto.ts
Normal 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 函数代替
|
||||||
39
src/modules/translator/translator-dto.ts
Normal file
39
src/modules/translator/translator-dto.ts
Normal 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 决定
|
||||||
|
}
|
||||||
0
src/modules/translator/translator-repository.ts
Normal file
0
src/modules/translator/translator-repository.ts
Normal file
0
src/modules/translator/translator-service-dto.ts
Normal file
0
src/modules/translator/translator-service-dto.ts
Normal 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
14
src/shared/constant.ts
Normal 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;
|
||||||
11
src/shared/dictionary-type.ts
Normal file
11
src/shared/dictionary-type.ts
Normal 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
23
src/shared/folder-type.ts
Normal 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
1
src/shared/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './dictionary-type';
|
||||||
25
src/utils/json.ts
Normal file
25
src/utils/json.ts
Normal 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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
export function isNonNegativeInteger(str: string): boolean {
|
export function isNonNegativeInteger(str: string): boolean {
|
||||||
return /^\d+$/.test(str);
|
return /^\d+$/.test(str);
|
||||||
}
|
}
|
||||||
@@ -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
1
src/utils/string.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export const stringNormalize = (s: string) => s.trim().toLowerCase();
|
||||||
13
src/utils/validate.ts
Normal file
13
src/utils/validate.ts
Normal 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);
|
||||||
Reference in New Issue
Block a user