mirror of
https://github.com/massbug/judge4c.git
synced 2025-07-03 23:30:50 +00:00
style: normalize quotes and indentation
This commit is contained in:
parent
055a532f3f
commit
c372856c3a
@ -1,9 +1,9 @@
|
||||
"use server";
|
||||
|
||||
import {
|
||||
OptimizeCodeInput,
|
||||
OptimizeCodeOutput,
|
||||
OptimizeCodeOutputSchema,
|
||||
OptimizeCodeInput,
|
||||
OptimizeCodeOutput,
|
||||
OptimizeCodeOutputSchema,
|
||||
} from "@/types/ai-improve";
|
||||
import { deepseek } from "@/lib/ai";
|
||||
import { CoreMessage, generateText } from "ai";
|
||||
@ -15,71 +15,77 @@ import prisma from "@/lib/prisma";
|
||||
* @returns 优化后的代码和说明
|
||||
*/
|
||||
export const optimizeCode = async (
|
||||
input: OptimizeCodeInput
|
||||
input: OptimizeCodeInput
|
||||
): Promise<OptimizeCodeOutput> => {
|
||||
const model = deepseek("chat");
|
||||
const model = deepseek("chat");
|
||||
|
||||
// 获取题目详情(如果提供了problemId)
|
||||
let problemDetails = "";
|
||||
// 获取题目详情(如果提供了problemId)
|
||||
let problemDetails = "";
|
||||
|
||||
if (input.problemId) {
|
||||
try {
|
||||
// 尝试获取英文描述
|
||||
const problemLocalizationEn = await prisma.problemLocalization.findUnique({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "en",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
});
|
||||
if (input.problemId) {
|
||||
try {
|
||||
// 尝试获取英文描述
|
||||
const problemLocalizationEn = await prisma.problemLocalization.findUnique(
|
||||
{
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "en",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (problemLocalizationEn) {
|
||||
problemDetails = `
|
||||
if (problemLocalizationEn) {
|
||||
problemDetails = `
|
||||
Problem Requirements:
|
||||
-------------------
|
||||
Description: ${problemLocalizationEn.content}
|
||||
`;
|
||||
} else {
|
||||
// 回退到中文描述
|
||||
const problemLocalizationZh = await prisma.problemLocalization.findUnique({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "zh",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// 回退到中文描述
|
||||
const problemLocalizationZh =
|
||||
await prisma.problemLocalization.findUnique({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "zh",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (problemLocalizationZh) {
|
||||
problemDetails = `
|
||||
if (problemLocalizationZh) {
|
||||
problemDetails = `
|
||||
Problem Requirements:
|
||||
-------------------
|
||||
Description: ${problemLocalizationZh.content}
|
||||
`;
|
||||
console.warn(`Fallback to Chinese description for problemId: ${input.problemId}`);
|
||||
} else {
|
||||
problemDetails = "Problem description not found in any language.";
|
||||
console.warn(`No description found for problemId: ${input.problemId}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch problem details:", error);
|
||||
problemDetails = "Error fetching problem description.";
|
||||
console.warn(
|
||||
`Fallback to Chinese description for problemId: ${input.problemId}`
|
||||
);
|
||||
} else {
|
||||
problemDetails = "Problem description not found in any language.";
|
||||
console.warn(
|
||||
`No description found for problemId: ${input.problemId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch problem details:", error);
|
||||
problemDetails = "Error fetching problem description.";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 构建AI提示词
|
||||
const prompt = `
|
||||
// 构建AI提示词
|
||||
const prompt = `
|
||||
Analyze the following programming code for potential errors, inefficiencies or code style issues.
|
||||
Provide an optimized version of the code with explanations. Focus on:
|
||||
1. Fixing any syntax errors
|
||||
@ -104,40 +110,40 @@ Format:
|
||||
"issuesFixed": ["list of issues fixed"]
|
||||
}
|
||||
`;
|
||||
console.log("Prompt:", prompt);
|
||||
console.log("Prompt:", prompt);
|
||||
|
||||
// 发送请求给OpenAI
|
||||
const messages: CoreMessage[] = [{ role: "user", content: prompt }];
|
||||
let text;
|
||||
try {
|
||||
const response = await generateText({
|
||||
model: model,
|
||||
messages: messages,
|
||||
});
|
||||
text = response.text;
|
||||
} catch (error) {
|
||||
console.error("Error generating text with OpenAI:", error);
|
||||
throw new Error("Failed to generate response from OpenAI");
|
||||
}
|
||||
// 发送请求给OpenAI
|
||||
const messages: CoreMessage[] = [{ role: "user", content: prompt }];
|
||||
let text;
|
||||
try {
|
||||
const response = await generateText({
|
||||
model: model,
|
||||
messages: messages,
|
||||
});
|
||||
text = response.text;
|
||||
} catch (error) {
|
||||
console.error("Error generating text with OpenAI:", error);
|
||||
throw new Error("Failed to generate response from OpenAI");
|
||||
}
|
||||
|
||||
// 解析LLM响应
|
||||
let llmResponseJson;
|
||||
try {
|
||||
const cleanedText = text.trim();
|
||||
llmResponseJson = JSON.parse(cleanedText);
|
||||
} catch (error) {
|
||||
console.error("Failed to parse LLM response as JSON:", error);
|
||||
console.error("LLM raw output:", text);
|
||||
throw new Error("Invalid JSON response from LLM");
|
||||
}
|
||||
// 解析LLM响应
|
||||
let llmResponseJson;
|
||||
try {
|
||||
const cleanedText = text.trim();
|
||||
llmResponseJson = JSON.parse(cleanedText);
|
||||
} catch (error) {
|
||||
console.error("Failed to parse LLM response as JSON:", error);
|
||||
console.error("LLM raw output:", text);
|
||||
throw new Error("Invalid JSON response from LLM");
|
||||
}
|
||||
|
||||
// 验证响应格式
|
||||
const validationResult = OptimizeCodeOutputSchema.safeParse(llmResponseJson);
|
||||
if (!validationResult.success) {
|
||||
console.error("Zod validation failed:", validationResult.error.format());
|
||||
throw new Error("Response validation failed");
|
||||
}
|
||||
// 验证响应格式
|
||||
const validationResult = OptimizeCodeOutputSchema.safeParse(llmResponseJson);
|
||||
if (!validationResult.success) {
|
||||
console.error("Zod validation failed:", validationResult.error.format());
|
||||
throw new Error("Response validation failed");
|
||||
}
|
||||
|
||||
console.log("LLM response:", llmResponseJson);
|
||||
return validationResult.data;
|
||||
};
|
||||
console.log("LLM response:", llmResponseJson);
|
||||
return validationResult.data;
|
||||
};
|
||||
|
@ -1,83 +1,91 @@
|
||||
"use server";
|
||||
|
||||
import {AITestCaseInput, AITestCaseOutput, AITestCaseOutputSchema} from "@/types/ai-testcase";
|
||||
import {
|
||||
AITestCaseInput,
|
||||
AITestCaseOutput,
|
||||
AITestCaseOutputSchema,
|
||||
} from "@/types/ai-testcase";
|
||||
|
||||
import { deepseek } from "@/lib/ai";
|
||||
import { CoreMessage, generateText } from "ai";
|
||||
import prisma from "@/lib/prisma";
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param input
|
||||
* @returns
|
||||
*/
|
||||
export const generateAITestcase = async (
|
||||
input: AITestCaseInput
|
||||
input: AITestCaseInput
|
||||
): Promise<AITestCaseOutput> => {
|
||||
const model = deepseek("deepseek-chat");
|
||||
const model = deepseek("deepseek-chat");
|
||||
|
||||
let problemDetails = "";
|
||||
let problemDetails = "";
|
||||
|
||||
if (input.problemId) {
|
||||
try {
|
||||
// 尝试获取英文描述
|
||||
const problemLocalizationEn = await prisma.problemLocalization.findUnique({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "en",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
});
|
||||
if (input.problemId) {
|
||||
try {
|
||||
// 尝试获取英文描述
|
||||
const problemLocalizationEn = await prisma.problemLocalization.findUnique(
|
||||
{
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "en",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (problemLocalizationEn) {
|
||||
problemDetails = `
|
||||
if (problemLocalizationEn) {
|
||||
problemDetails = `
|
||||
Problem Requirements:
|
||||
-------------------
|
||||
Description: ${problemLocalizationEn.content}
|
||||
`;
|
||||
} else {
|
||||
// 回退到中文描述
|
||||
const problemLocalizationZh = await prisma.problemLocalization.findUnique({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "zh",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// 回退到中文描述
|
||||
const problemLocalizationZh =
|
||||
await prisma.problemLocalization.findUnique({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: input.problemId,
|
||||
locale: "zh",
|
||||
type: "DESCRIPTION",
|
||||
},
|
||||
},
|
||||
include: {
|
||||
problem: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (problemLocalizationZh) {
|
||||
problemDetails = `
|
||||
if (problemLocalizationZh) {
|
||||
problemDetails = `
|
||||
Problem Requirements:
|
||||
-------------------
|
||||
Description: ${problemLocalizationZh.content}
|
||||
`;
|
||||
console.warn(`Fallback to Chinese description for problemId: ${input.problemId}`);
|
||||
} else {
|
||||
problemDetails = "Problem description not found in any language.";
|
||||
console.warn(`No description found for problemId: ${input.problemId}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch problem details:", error);
|
||||
problemDetails = "Error fetching problem description.";
|
||||
console.warn(
|
||||
`Fallback to Chinese description for problemId: ${input.problemId}`
|
||||
);
|
||||
} else {
|
||||
problemDetails = "Problem description not found in any language.";
|
||||
console.warn(
|
||||
`No description found for problemId: ${input.problemId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch problem details:", error);
|
||||
problemDetails = "Error fetching problem description.";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 构建AI提示词
|
||||
const prompt = `
|
||||
// 构建AI提示词
|
||||
const prompt = `
|
||||
Analyze the problem statement to get the expected input structure, constraints, and output logic. Generate **novel, randomized** inputs/outputs that strictly adhere to the problem's requirements. Focus on:
|
||||
Your entire response/output is going to consist of a single JSON object {}, and you will NOT wrap it within JSON Markdown markers.
|
||||
|
||||
@ -111,40 +119,37 @@ Respond **ONLY** with this JSON structure.
|
||||
|
||||
`;
|
||||
|
||||
// 发送请求给OpenAI
|
||||
const messages: CoreMessage[] = [{ role: "user", content: prompt }];
|
||||
let text;
|
||||
try {
|
||||
const response = await generateText({
|
||||
model: model,
|
||||
messages: messages,
|
||||
});
|
||||
text = response.text;
|
||||
} catch (error) {
|
||||
console.error("Error generating text with OpenAI:", error);
|
||||
throw new Error("Failed to generate response from OpenAI");
|
||||
}
|
||||
// 发送请求给OpenAI
|
||||
const messages: CoreMessage[] = [{ role: "user", content: prompt }];
|
||||
let text;
|
||||
try {
|
||||
const response = await generateText({
|
||||
model: model,
|
||||
messages: messages,
|
||||
});
|
||||
text = response.text;
|
||||
} catch (error) {
|
||||
console.error("Error generating text with OpenAI:", error);
|
||||
throw new Error("Failed to generate response from OpenAI");
|
||||
}
|
||||
|
||||
// 解析LLM响应
|
||||
let llmResponseJson;
|
||||
try {
|
||||
llmResponseJson = JSON.parse(text)
|
||||
// 解析LLM响应
|
||||
let llmResponseJson;
|
||||
try {
|
||||
llmResponseJson = JSON.parse(text);
|
||||
} catch (error) {
|
||||
console.error("Failed to parse LLM response as JSON:", error);
|
||||
console.error("LLM raw output:", text);
|
||||
throw new Error("Invalid JSON response from LLM");
|
||||
}
|
||||
|
||||
// 验证响应格式
|
||||
const validationResult = AITestCaseOutputSchema.safeParse(llmResponseJson);
|
||||
if (!validationResult.success) {
|
||||
console.error("Zod validation failed:", validationResult.error.format());
|
||||
throw new Error("Response validation failed");
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error("Failed to parse LLM response as JSON:", error);
|
||||
console.error("LLM raw output:", text);
|
||||
throw new Error("Invalid JSON response from LLM");
|
||||
}
|
||||
|
||||
|
||||
// 验证响应格式
|
||||
const validationResult = AITestCaseOutputSchema.safeParse(llmResponseJson);
|
||||
if (!validationResult.success) {
|
||||
console.error("Zod validation failed:", validationResult.error.format());
|
||||
throw new Error("Response validation failed");
|
||||
}
|
||||
|
||||
console.log("LLM response:", llmResponseJson);
|
||||
return validationResult.data;
|
||||
};
|
||||
console.log("LLM response:", llmResponseJson);
|
||||
return validationResult.data;
|
||||
};
|
||||
|
@ -1,63 +1,63 @@
|
||||
// app/actions/get-problem-data.ts
|
||||
'use server';
|
||||
"use server";
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { Locale } from '@/generated/client';
|
||||
import { serialize } from 'next-mdx-remote/serialize';
|
||||
import prisma from "@/lib/prisma";
|
||||
import { Locale } from "@/generated/client";
|
||||
import { serialize } from "next-mdx-remote/serialize";
|
||||
|
||||
export async function getProblemData(problemId: string, locale?: string) {
|
||||
const selectedLocale = locale as Locale;
|
||||
const selectedLocale = locale as Locale;
|
||||
|
||||
const problem = await prisma.problem.findUnique({
|
||||
where: { id: problemId },
|
||||
include: {
|
||||
templates: true,
|
||||
testcases: {
|
||||
include: { inputs: true }
|
||||
},
|
||||
localizations: {
|
||||
where: {
|
||||
locale: selectedLocale,
|
||||
},
|
||||
},
|
||||
const problem = await prisma.problem.findUnique({
|
||||
where: { id: problemId },
|
||||
include: {
|
||||
templates: true,
|
||||
testcases: {
|
||||
include: { inputs: true },
|
||||
},
|
||||
localizations: {
|
||||
where: {
|
||||
locale: selectedLocale,
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!problem) {
|
||||
throw new Error('Problem not found');
|
||||
}
|
||||
if (!problem) {
|
||||
throw new Error("Problem not found");
|
||||
}
|
||||
|
||||
const getContent = (type: string) =>
|
||||
problem.localizations.find(loc => loc.type === type)?.content || '';
|
||||
const getContent = (type: string) =>
|
||||
problem.localizations.find((loc) => loc.type === type)?.content || "";
|
||||
|
||||
const rawDescription = getContent('DESCRIPTION');
|
||||
const rawDescription = getContent("DESCRIPTION");
|
||||
|
||||
const mdxDescription = await serialize(rawDescription, {
|
||||
parseFrontmatter: false,
|
||||
});
|
||||
const mdxDescription = await serialize(rawDescription, {
|
||||
parseFrontmatter: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id: problem.id,
|
||||
displayId: problem.displayId,
|
||||
difficulty: problem.difficulty,
|
||||
isPublished: problem.isPublished,
|
||||
timeLimit: problem.timeLimit,
|
||||
memoryLimit: problem.memoryLimit,
|
||||
title: getContent('TITLE'),
|
||||
description: rawDescription,
|
||||
mdxDescription,
|
||||
solution: getContent('SOLUTION'),
|
||||
templates: problem.templates.map(t => ({
|
||||
language: t.language,
|
||||
content: t.content,
|
||||
})),
|
||||
testcases: problem.testcases.map(tc => ({
|
||||
id: tc.id,
|
||||
expectedOutput: tc.expectedOutput,
|
||||
inputs: tc.inputs.map(input => ({
|
||||
name: input.name,
|
||||
value: input.value,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
return {
|
||||
id: problem.id,
|
||||
displayId: problem.displayId,
|
||||
difficulty: problem.difficulty,
|
||||
isPublished: problem.isPublished,
|
||||
timeLimit: problem.timeLimit,
|
||||
memoryLimit: problem.memoryLimit,
|
||||
title: getContent("TITLE"),
|
||||
description: rawDescription,
|
||||
mdxDescription,
|
||||
solution: getContent("SOLUTION"),
|
||||
templates: problem.templates.map((t) => ({
|
||||
language: t.language,
|
||||
content: t.content,
|
||||
})),
|
||||
testcases: problem.testcases.map((tc) => ({
|
||||
id: tc.id,
|
||||
expectedOutput: tc.expectedOutput,
|
||||
inputs: tc.inputs.map((input) => ({
|
||||
name: input.name,
|
||||
value: input.value,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
@ -1,14 +1,14 @@
|
||||
// src/app/actions/getProblemLocales.ts
|
||||
'use server';
|
||||
"use server";
|
||||
|
||||
import prisma from "@/lib/prisma";
|
||||
|
||||
export async function getProblemLocales(problemId: string): Promise<string[]> {
|
||||
const locales = await prisma.problemLocalization.findMany({
|
||||
where: { problemId },
|
||||
select: { locale: true },
|
||||
distinct: ['locale'],
|
||||
});
|
||||
const locales = await prisma.problemLocalization.findMany({
|
||||
where: { problemId },
|
||||
select: { locale: true },
|
||||
distinct: ["locale"],
|
||||
});
|
||||
|
||||
return locales.map(l => l.locale);
|
||||
return locales.map((l) => l.locale);
|
||||
}
|
||||
|
@ -19,24 +19,27 @@ interface AIEditorWrapperProps {
|
||||
}
|
||||
|
||||
export const AIEditorWrapper = ({
|
||||
language,
|
||||
value,
|
||||
path,
|
||||
problemId,
|
||||
languageServerConfigs,
|
||||
onChange,
|
||||
// className,
|
||||
}: AIEditorWrapperProps) => {
|
||||
language,
|
||||
value,
|
||||
path,
|
||||
problemId,
|
||||
languageServerConfigs,
|
||||
onChange,
|
||||
}: // className,
|
||||
AIEditorWrapperProps) => {
|
||||
const [currentCode, setCurrentCode] = useState(value ?? "");
|
||||
const [optimizedCode, setOptimizedCode] = useState("");
|
||||
const [isOptimizing, setIsOptimizing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showDiff, setShowDiff] = useState(false);
|
||||
|
||||
const handleCodeChange = useCallback((val: string) => {
|
||||
setCurrentCode(val);
|
||||
onChange?.(val);
|
||||
}, [onChange]);
|
||||
const handleCodeChange = useCallback(
|
||||
(val: string) => {
|
||||
setCurrentCode(val);
|
||||
onChange?.(val);
|
||||
},
|
||||
[onChange]
|
||||
);
|
||||
|
||||
const handleOptimize = useCallback(async () => {
|
||||
if (!problemId || !currentCode) return;
|
||||
@ -66,59 +69,59 @@ export const AIEditorWrapper = ({
|
||||
}, [optimizedCode, onChange]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full w-full">
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<button
|
||||
onClick={handleOptimize}
|
||||
disabled={isOptimizing}
|
||||
className="px-4 py-2 bg-primary text-white rounded hover:bg-primary/90"
|
||||
>
|
||||
{isOptimizing ? "优化中..." : "AI优化代码"}
|
||||
</button>
|
||||
<div className="flex flex-col h-full w-full">
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<button
|
||||
onClick={handleOptimize}
|
||||
disabled={isOptimizing}
|
||||
className="px-4 py-2 bg-primary text-white rounded hover:bg-primary/90"
|
||||
>
|
||||
{isOptimizing ? "优化中..." : "AI优化代码"}
|
||||
</button>
|
||||
|
||||
{showDiff && (
|
||||
<div className="space-x-2">
|
||||
<button
|
||||
onClick={() => setShowDiff(false)}
|
||||
className="px-4 py-2 bg-secondary text-white rounded"
|
||||
>
|
||||
隐藏对比
|
||||
</button>
|
||||
<button
|
||||
onClick={handleApplyOptimized}
|
||||
className="px-4 py-2 bg-green-500 text-white rounded"
|
||||
>
|
||||
应用优化结果
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 text-red-600 rounded-md">{error}</div>
|
||||
{showDiff && (
|
||||
<div className="space-x-2">
|
||||
<button
|
||||
onClick={() => setShowDiff(false)}
|
||||
className="px-4 py-2 bg-secondary text-white rounded"
|
||||
>
|
||||
隐藏对比
|
||||
</button>
|
||||
<button
|
||||
onClick={handleApplyOptimized}
|
||||
className="px-4 py-2 bg-green-500 text-white rounded"
|
||||
>
|
||||
应用优化结果
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-grow overflow-hidden">
|
||||
{showDiff ? (
|
||||
<DiffEditor
|
||||
original={currentCode}
|
||||
modified={optimizedCode}
|
||||
language={language}
|
||||
theme="vs-dark"
|
||||
className="h-full w-full"
|
||||
options={{ readOnly: true, minimap: { enabled: false } }}
|
||||
/>
|
||||
) : (
|
||||
<CoreEditor
|
||||
language={language}
|
||||
value={currentCode}
|
||||
path={path}
|
||||
languageServerConfigs={languageServerConfigs}
|
||||
onChange={handleCodeChange}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-100 text-red-600 rounded-md">{error}</div>
|
||||
)}
|
||||
|
||||
<div className="flex-grow overflow-hidden">
|
||||
{showDiff ? (
|
||||
<DiffEditor
|
||||
original={currentCode}
|
||||
modified={optimizedCode}
|
||||
language={language}
|
||||
theme="vs-dark"
|
||||
className="h-full w-full"
|
||||
options={{ readOnly: true, minimap: { enabled: false } }}
|
||||
/>
|
||||
) : (
|
||||
<CoreEditor
|
||||
language={language}
|
||||
value={currentCode}
|
||||
path={path}
|
||||
languageServerConfigs={languageServerConfigs}
|
||||
onChange={handleCodeChange}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
@ -1,14 +1,14 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { getProblemData } from '@/app/actions/getProblem';
|
||||
import { updateProblemTemplate } from '@/components/creater/problem-maintain';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { CoreEditor } from '@/components/core-editor';
|
||||
import { Language } from '@/generated/client';
|
||||
import { toast } from 'sonner';
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { getProblemData } from "@/app/actions/getProblem";
|
||||
import { updateProblemTemplate } from "@/components/creater/problem-maintain";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { CoreEditor } from "@/components/core-editor";
|
||||
import { Language } from "@/generated/client";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface Template {
|
||||
language: string;
|
||||
@ -21,7 +21,7 @@ interface EditCodePanelProps {
|
||||
|
||||
export default function EditCodePanel({ problemId }: EditCodePanelProps) {
|
||||
const [codeTemplate, setCodeTemplate] = useState<Template>({
|
||||
language: 'cpp',
|
||||
language: "cpp",
|
||||
content: `// 默认代码模板 for Problem ${problemId}`,
|
||||
});
|
||||
const [templates, setTemplates] = useState<Template[]>([]);
|
||||
@ -31,79 +31,81 @@ export default function EditCodePanel({ problemId }: EditCodePanelProps) {
|
||||
try {
|
||||
const problem = await getProblemData(problemId);
|
||||
setTemplates(problem.templates);
|
||||
const sel = problem.templates.find(t => t.language === 'cpp') || problem.templates[0];
|
||||
const sel =
|
||||
problem.templates.find((t) => t.language === "cpp") ||
|
||||
problem.templates[0];
|
||||
if (sel) setCodeTemplate(sel);
|
||||
} catch (err) {
|
||||
console.error('加载问题数据失败:', err);
|
||||
toast.error('加载问题数据失败');
|
||||
console.error("加载问题数据失败:", err);
|
||||
toast.error("加载问题数据失败");
|
||||
}
|
||||
}
|
||||
fetchTemplates();
|
||||
}, [problemId]);
|
||||
|
||||
const handleLanguageChange = (language: string) => {
|
||||
const sel = templates.find(t => t.language === language);
|
||||
const sel = templates.find((t) => t.language === language);
|
||||
if (sel) setCodeTemplate(sel);
|
||||
};
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
try {
|
||||
const res = await updateProblemTemplate(
|
||||
problemId,
|
||||
codeTemplate.language as Language,
|
||||
codeTemplate.content
|
||||
problemId,
|
||||
codeTemplate.language as Language,
|
||||
codeTemplate.content
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success('保存成功');
|
||||
toast.success("保存成功");
|
||||
} else {
|
||||
toast.error('保存失败');
|
||||
toast.error("保存失败");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('保存异常:', error);
|
||||
toast.error('保存异常');
|
||||
console.error("保存异常:", error);
|
||||
toast.error("保存异常");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>代码模板</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="language-select">编程语言</Label>
|
||||
<select
|
||||
id="language-select"
|
||||
className="block w-full p-2 border border-gray-300 rounded-md dark:bg-gray-800 dark:border-gray-700"
|
||||
value={codeTemplate.language}
|
||||
onChange={e => handleLanguageChange(e.target.value)}
|
||||
>
|
||||
{templates.map(t => (
|
||||
<option key={t.language} value={t.language}>
|
||||
{t.language.toUpperCase()}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="code-editor">代码模板内容</Label>
|
||||
<div className="border rounded-md h-[500px]">
|
||||
<CoreEditor
|
||||
language={codeTemplate.language}
|
||||
value={codeTemplate.content}
|
||||
path={`/${problemId}.${codeTemplate.language}`}
|
||||
onChange={value =>
|
||||
setCodeTemplate({ ...codeTemplate, content: value || '' })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button onClick={handleSave}>保存代码模板</Button>
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>代码模板</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="language-select">编程语言</Label>
|
||||
<select
|
||||
id="language-select"
|
||||
className="block w-full p-2 border border-gray-300 rounded-md dark:bg-gray-800 dark:border-gray-700"
|
||||
value={codeTemplate.language}
|
||||
onChange={(e) => handleLanguageChange(e.target.value)}
|
||||
>
|
||||
{templates.map((t) => (
|
||||
<option key={t.language} value={t.language}>
|
||||
{t.language.toUpperCase()}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="code-editor">代码模板内容</Label>
|
||||
<div className="border rounded-md h-[500px]">
|
||||
<CoreEditor
|
||||
language={codeTemplate.language}
|
||||
value={codeTemplate.content}
|
||||
path={`/${problemId}.${codeTemplate.language}`}
|
||||
onChange={(value) =>
|
||||
setCodeTemplate({ ...codeTemplate, content: value || "" })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button onClick={handleSave}>保存代码模板</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
@ -12,16 +12,25 @@ import { getProblemLocales } from "@/app/actions/getProblemLocales";
|
||||
import { Accordion } from "@/components/ui/accordion";
|
||||
import { VideoEmbed } from "@/components/content/video-embed";
|
||||
import { toast } from "sonner";
|
||||
import { updateProblemDescription, updateProblemTitle } from '@/components/creater/problem-maintain';
|
||||
import {
|
||||
updateProblemDescription,
|
||||
updateProblemTitle,
|
||||
} from "@/components/creater/problem-maintain";
|
||||
import { Locale } from "@/generated/client";
|
||||
|
||||
export default function EditDescriptionPanel({ problemId }: { problemId: string }) {
|
||||
export default function EditDescriptionPanel({
|
||||
problemId,
|
||||
}: {
|
||||
problemId: string;
|
||||
}) {
|
||||
const [locales, setLocales] = useState<string[]>([]);
|
||||
const [currentLocale, setCurrentLocale] = useState<string>("");
|
||||
const [customLocale, setCustomLocale] = useState("");
|
||||
|
||||
const [description, setDescription] = useState({ title: "", content: "" });
|
||||
const [viewMode, setViewMode] = useState<"edit" | "preview" | "compare">("edit");
|
||||
const [viewMode, setViewMode] = useState<"edit" | "preview" | "compare">(
|
||||
"edit"
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchLocales() {
|
||||
@ -31,7 +40,7 @@ export default function EditDescriptionPanel({ problemId }: { problemId: string
|
||||
if (langs.length > 0) setCurrentLocale(langs[0]);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error('获取语言列表失败');
|
||||
toast.error("获取语言列表失败");
|
||||
}
|
||||
}
|
||||
fetchLocales();
|
||||
@ -42,10 +51,13 @@ export default function EditDescriptionPanel({ problemId }: { problemId: string
|
||||
async function fetchProblem() {
|
||||
try {
|
||||
const data = await getProblemData(problemId, currentLocale);
|
||||
setDescription({ title: data?.title || "", content: data?.description || "" });
|
||||
setDescription({
|
||||
title: data?.title || "",
|
||||
content: data?.description || "",
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error('加载题目描述失败');
|
||||
toast.error("加载题目描述失败");
|
||||
}
|
||||
}
|
||||
fetchProblem();
|
||||
@ -63,111 +75,134 @@ export default function EditDescriptionPanel({ problemId }: { problemId: string
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
if (!currentLocale) {
|
||||
toast.error('请选择语言');
|
||||
toast.error("请选择语言");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const locale = currentLocale as Locale;
|
||||
const resTitle = await updateProblemTitle(problemId, locale, description.title);
|
||||
const resDesc = await updateProblemDescription(problemId, locale, description.content);
|
||||
const resTitle = await updateProblemTitle(
|
||||
problemId,
|
||||
locale,
|
||||
description.title
|
||||
);
|
||||
const resDesc = await updateProblemDescription(
|
||||
problemId,
|
||||
locale,
|
||||
description.content
|
||||
);
|
||||
if (resTitle.success && resDesc.success) {
|
||||
toast.success('保存成功');
|
||||
toast.success("保存成功");
|
||||
} else {
|
||||
toast.error('保存失败');
|
||||
toast.error("保存失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error('保存异常');
|
||||
toast.error("保存异常");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>题目描述</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* 语言切换 */}
|
||||
<div className="space-y-2">
|
||||
<Label>选择语言</Label>
|
||||
<div className="flex space-x-2">
|
||||
<select
|
||||
value={currentLocale}
|
||||
onChange={(e) => setCurrentLocale(e.target.value)}
|
||||
className="border rounded-md px-3 py-2"
|
||||
>
|
||||
{locales.map((locale) => (
|
||||
<option key={locale} value={locale}>
|
||||
{locale}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Input
|
||||
placeholder="添加新语言"
|
||||
value={customLocale}
|
||||
onChange={(e) => setCustomLocale(e.target.value)}
|
||||
/>
|
||||
<Button onClick={handleAddCustomLocale}>添加</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 标题输入 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description-title">标题</Label>
|
||||
<Input
|
||||
id="description-title"
|
||||
value={description.title}
|
||||
onChange={(e) => setDescription({ ...description, title: e.target.value })}
|
||||
placeholder="输入题目标题"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 编辑/预览切换 */}
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>题目描述</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* 语言切换 */}
|
||||
<div className="space-y-2">
|
||||
<Label>选择语言</Label>
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "edit" ? "default" : "outline"}
|
||||
onClick={() => setViewMode("edit")}
|
||||
<select
|
||||
value={currentLocale}
|
||||
onChange={(e) => setCurrentLocale(e.target.value)}
|
||||
className="border rounded-md px-3 py-2"
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "preview" ? "default" : "outline"}
|
||||
onClick={() => setViewMode(viewMode === "preview" ? "edit" : "preview")}
|
||||
>
|
||||
{viewMode === "preview" ? "取消" : "预览"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "compare" ? "default" : "outline"}
|
||||
onClick={() => setViewMode("compare")}
|
||||
>
|
||||
对比
|
||||
</Button>
|
||||
{locales.map((locale) => (
|
||||
<option key={locale} value={locale}>
|
||||
{locale}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Input
|
||||
placeholder="添加新语言"
|
||||
value={customLocale}
|
||||
onChange={(e) => setCustomLocale(e.target.value)}
|
||||
/>
|
||||
<Button onClick={handleAddCustomLocale}>添加</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 编辑/预览区域 */}
|
||||
<div className={viewMode === "compare" ? "grid grid-cols-2 gap-6" : "flex flex-col gap-6"}>
|
||||
{(viewMode === "edit" || viewMode === "compare") && (
|
||||
<div className="relative h-[600px]">
|
||||
<CoreEditor
|
||||
value={description.content}
|
||||
onChange={(newVal) => setDescription({ ...description, content: newVal || "" })}
|
||||
language="markdown"
|
||||
className="absolute inset-0 rounded-md border border-input"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{viewMode !== "edit" && (
|
||||
<div className="prose dark:prose-invert">
|
||||
<MdxPreview source={description.content} components={{ Accordion, VideoEmbed }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* 标题输入 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description-title">标题</Label>
|
||||
<Input
|
||||
id="description-title"
|
||||
value={description.title}
|
||||
onChange={(e) =>
|
||||
setDescription({ ...description, title: e.target.value })
|
||||
}
|
||||
placeholder="输入题目标题"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button onClick={handleSave}>保存更改</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* 编辑/预览切换 */}
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "edit" ? "default" : "outline"}
|
||||
onClick={() => setViewMode("edit")}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "preview" ? "default" : "outline"}
|
||||
onClick={() =>
|
||||
setViewMode(viewMode === "preview" ? "edit" : "preview")
|
||||
}
|
||||
>
|
||||
{viewMode === "preview" ? "取消" : "预览"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "compare" ? "default" : "outline"}
|
||||
onClick={() => setViewMode("compare")}
|
||||
>
|
||||
对比
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 编辑/预览区域 */}
|
||||
<div
|
||||
className={
|
||||
viewMode === "compare"
|
||||
? "grid grid-cols-2 gap-6"
|
||||
: "flex flex-col gap-6"
|
||||
}
|
||||
>
|
||||
{(viewMode === "edit" || viewMode === "compare") && (
|
||||
<div className="relative h-[600px]">
|
||||
<CoreEditor
|
||||
value={description.content}
|
||||
onChange={(newVal) =>
|
||||
setDescription({ ...description, content: newVal || "" })
|
||||
}
|
||||
language="markdown"
|
||||
className="absolute inset-0 rounded-md border border-input"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{viewMode !== "edit" && (
|
||||
<div className="prose dark:prose-invert">
|
||||
<MdxPreview
|
||||
source={description.content}
|
||||
components={{ Accordion, VideoEmbed }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button onClick={handleSave}>保存更改</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { getProblemData } from "@/app/actions/getProblem";
|
||||
import { toast } from "sonner";
|
||||
import { updateProblemDetail } from '@/components/creater/problem-maintain';
|
||||
import { updateProblemDetail } from "@/components/creater/problem-maintain";
|
||||
import { Difficulty } from "@/generated/client";
|
||||
|
||||
export default function EditDetailPanel({ problemId }: { problemId: string }) {
|
||||
@ -32,15 +32,15 @@ export default function EditDetailPanel({ problemId }: { problemId: string }) {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("获取题目信息失败:", error);
|
||||
toast.error('加载详情失败');
|
||||
toast.error("加载详情失败");
|
||||
}
|
||||
}
|
||||
fetchData();
|
||||
}, [problemId]);
|
||||
|
||||
const handleNumberInputChange = (
|
||||
e: React.ChangeEvent<HTMLInputElement>,
|
||||
field: keyof typeof problemDetails
|
||||
e: React.ChangeEvent<HTMLInputElement>,
|
||||
field: keyof typeof problemDetails
|
||||
) => {
|
||||
const value = parseInt(e.target.value, 10);
|
||||
if (!isNaN(value)) {
|
||||
@ -66,92 +66,95 @@ export default function EditDetailPanel({ problemId }: { problemId: string }) {
|
||||
isPublished: problemDetails.isPublished,
|
||||
});
|
||||
if (res.success) {
|
||||
toast.success('保存成功');
|
||||
toast.success("保存成功");
|
||||
} else {
|
||||
toast.error('保存失败');
|
||||
toast.error("保存失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('保存异常:', err);
|
||||
toast.error('保存异常');
|
||||
console.error("保存异常:", err);
|
||||
toast.error("保存异常");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>题目详情</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="display-id">显示ID</Label>
|
||||
<Input
|
||||
id="display-id"
|
||||
type="number"
|
||||
value={problemDetails.displayId}
|
||||
onChange={(e) => handleNumberInputChange(e, "displayId")}
|
||||
placeholder="输入显示ID"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="difficulty-select">难度等级</Label>
|
||||
<select
|
||||
id="difficulty-select"
|
||||
className="block w-full p-2 border border-gray-300 rounded-md dark:bg-gray-800 dark:border-gray-700"
|
||||
value={problemDetails.difficulty}
|
||||
onChange={handleDifficultyChange}
|
||||
>
|
||||
<option value="EASY">简单</option>
|
||||
<option value="MEDIUM">中等</option>
|
||||
<option value="HARD">困难</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="time-limit">时间限制 (ms)</Label>
|
||||
<Input
|
||||
id="time-limit"
|
||||
type="number"
|
||||
value={problemDetails.timeLimit}
|
||||
onChange={(e) => handleNumberInputChange(e, "timeLimit")}
|
||||
placeholder="输入时间限制"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="memory-limit">内存限制 (字节)</Label>
|
||||
<Input
|
||||
id="memory-limit"
|
||||
type="number"
|
||||
value={problemDetails.memoryLimit}
|
||||
onChange={(e) => handleNumberInputChange(e, "memoryLimit")}
|
||||
placeholder="输入内存限制"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
id="is-published"
|
||||
type="checkbox"
|
||||
checked={problemDetails.isPublished}
|
||||
onChange={(e) =>
|
||||
setProblemDetails({ ...problemDetails, isPublished: e.target.checked })
|
||||
}
|
||||
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 focus:ring-2"
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>题目详情</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="display-id">显示ID</Label>
|
||||
<Input
|
||||
id="display-id"
|
||||
type="number"
|
||||
value={problemDetails.displayId}
|
||||
onChange={(e) => handleNumberInputChange(e, "displayId")}
|
||||
placeholder="输入显示ID"
|
||||
/>
|
||||
<Label htmlFor="is-published" className="text-sm font-medium">
|
||||
是否发布
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button type="button" onClick={handleSave}>
|
||||
保存更改
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="difficulty-select">难度等级</Label>
|
||||
<select
|
||||
id="difficulty-select"
|
||||
className="block w-full p-2 border border-gray-300 rounded-md dark:bg-gray-800 dark:border-gray-700"
|
||||
value={problemDetails.difficulty}
|
||||
onChange={handleDifficultyChange}
|
||||
>
|
||||
<option value="EASY">简单</option>
|
||||
<option value="MEDIUM">中等</option>
|
||||
<option value="HARD">困难</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="time-limit">时间限制 (ms)</Label>
|
||||
<Input
|
||||
id="time-limit"
|
||||
type="number"
|
||||
value={problemDetails.timeLimit}
|
||||
onChange={(e) => handleNumberInputChange(e, "timeLimit")}
|
||||
placeholder="输入时间限制"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="memory-limit">内存限制 (字节)</Label>
|
||||
<Input
|
||||
id="memory-limit"
|
||||
type="number"
|
||||
value={problemDetails.memoryLimit}
|
||||
onChange={(e) => handleNumberInputChange(e, "memoryLimit")}
|
||||
placeholder="输入内存限制"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
id="is-published"
|
||||
type="checkbox"
|
||||
checked={problemDetails.isPublished}
|
||||
onChange={(e) =>
|
||||
setProblemDetails({
|
||||
...problemDetails,
|
||||
isPublished: e.target.checked,
|
||||
})
|
||||
}
|
||||
className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 focus:ring-2"
|
||||
/>
|
||||
<Label htmlFor="is-published" className="text-sm font-medium">
|
||||
是否发布
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button type="button" onClick={handleSave}>
|
||||
保存更改
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
@ -12,16 +12,22 @@ import { getProblemLocales } from "@/app/actions/getProblemLocales";
|
||||
import { Accordion } from "@/components/ui/accordion";
|
||||
import { VideoEmbed } from "@/components/content/video-embed";
|
||||
import { toast } from "sonner";
|
||||
import { updateProblemSolution } from '@/components/creater/problem-maintain';
|
||||
import { updateProblemSolution } from "@/components/creater/problem-maintain";
|
||||
import { Locale } from "@/generated/client";
|
||||
|
||||
export default function EditSolutionPanel({ problemId }: { problemId: string }) {
|
||||
export default function EditSolutionPanel({
|
||||
problemId,
|
||||
}: {
|
||||
problemId: string;
|
||||
}) {
|
||||
const [locales, setLocales] = useState<string[]>([]);
|
||||
const [currentLocale, setCurrentLocale] = useState<string>("");
|
||||
const [customLocale, setCustomLocale] = useState("");
|
||||
|
||||
const [solution, setSolution] = useState({ title: "", content: "" });
|
||||
const [viewMode, setViewMode] = useState<"edit" | "preview" | "compare">("edit");
|
||||
const [viewMode, setViewMode] = useState<"edit" | "preview" | "compare">(
|
||||
"edit"
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchLocales() {
|
||||
@ -31,7 +37,7 @@ export default function EditSolutionPanel({ problemId }: { problemId: string })
|
||||
if (langs.length > 0) setCurrentLocale(langs[0]);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error('获取语言列表失败');
|
||||
toast.error("获取语言列表失败");
|
||||
}
|
||||
}
|
||||
fetchLocales();
|
||||
@ -42,10 +48,13 @@ export default function EditSolutionPanel({ problemId }: { problemId: string })
|
||||
async function fetchSolution() {
|
||||
try {
|
||||
const data = await getProblemData(problemId, currentLocale);
|
||||
setSolution({ title: (data?.title || "") + " 解析", content: data?.solution || "" });
|
||||
setSolution({
|
||||
title: (data?.title || "") + " 解析",
|
||||
content: data?.solution || "",
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error('加载题目解析失败');
|
||||
toast.error("加载题目解析失败");
|
||||
}
|
||||
}
|
||||
fetchSolution();
|
||||
@ -53,7 +62,7 @@ export default function EditSolutionPanel({ problemId }: { problemId: string })
|
||||
|
||||
const handleAddCustomLocale = () => {
|
||||
if (customLocale && !locales.includes(customLocale)) {
|
||||
setLocales(prev => [...prev, customLocale]);
|
||||
setLocales((prev) => [...prev, customLocale]);
|
||||
setCurrentLocale(customLocale);
|
||||
setCustomLocale("");
|
||||
setSolution({ title: "", content: "" });
|
||||
@ -62,95 +71,134 @@ export default function EditSolutionPanel({ problemId }: { problemId: string })
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
if (!currentLocale) {
|
||||
toast.error('请选择语言');
|
||||
toast.error("请选择语言");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const locale = currentLocale as Locale;
|
||||
const res = await updateProblemSolution(problemId, locale, solution.content);
|
||||
const res = await updateProblemSolution(
|
||||
problemId,
|
||||
locale,
|
||||
solution.content
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success('保存成功');
|
||||
toast.success("保存成功");
|
||||
} else {
|
||||
toast.error('保存失败');
|
||||
toast.error("保存失败");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error('保存异常');
|
||||
toast.error("保存异常");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>题目解析</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* 语言切换 */}
|
||||
<div className="space-y-2">
|
||||
<Label>选择语言</Label>
|
||||
<div className="flex space-x-2">
|
||||
<select
|
||||
value={currentLocale}
|
||||
onChange={(e) => setCurrentLocale(e.target.value)}
|
||||
className="border rounded-md px-3 py-2"
|
||||
>
|
||||
{locales.map((locale) => (
|
||||
<option key={locale} value={locale}>
|
||||
{locale}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Input
|
||||
placeholder="添加新语言"
|
||||
value={customLocale}
|
||||
onChange={(e) => setCustomLocale(e.target.value)}
|
||||
/>
|
||||
<Button type="button" onClick={handleAddCustomLocale}>添加</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 标题输入 (仅展示) */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="solution-title">题解标题</Label>
|
||||
<Input
|
||||
id="solution-title"
|
||||
value={solution.title}
|
||||
onChange={(e) => setSolution({ ...solution, title: e.target.value })}
|
||||
placeholder="输入题解标题"
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 编辑/预览切换 */}
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>题目解析</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* 语言切换 */}
|
||||
<div className="space-y-2">
|
||||
<Label>选择语言</Label>
|
||||
<div className="flex space-x-2">
|
||||
<Button type="button" variant={viewMode === "edit" ? "default" : "outline"} onClick={() => setViewMode("edit")}>编辑</Button>
|
||||
<Button type="button" variant={viewMode === "preview" ? "default" : "outline"} onClick={() => setViewMode(viewMode === "preview" ? "edit" : "preview")}>
|
||||
{viewMode === "preview" ? "取消" : "预览"}
|
||||
<select
|
||||
value={currentLocale}
|
||||
onChange={(e) => setCurrentLocale(e.target.value)}
|
||||
className="border rounded-md px-3 py-2"
|
||||
>
|
||||
{locales.map((locale) => (
|
||||
<option key={locale} value={locale}>
|
||||
{locale}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Input
|
||||
placeholder="添加新语言"
|
||||
value={customLocale}
|
||||
onChange={(e) => setCustomLocale(e.target.value)}
|
||||
/>
|
||||
<Button type="button" onClick={handleAddCustomLocale}>
|
||||
添加
|
||||
</Button>
|
||||
<Button type="button" variant={viewMode === "compare" ? "default" : "outline"} onClick={() => setViewMode("compare")}>对比</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 编辑/预览区域 */}
|
||||
<div className={viewMode === "compare" ? "grid grid-cols-2 gap-6" : "flex flex-col gap-6"}>
|
||||
{(viewMode === "edit" || viewMode === "compare") && (
|
||||
<div className="relative h-[600px]">
|
||||
<CoreEditor
|
||||
value={solution.content}
|
||||
onChange={(val) => setSolution({ ...solution, content: val || "" })}
|
||||
language="markdown"
|
||||
className="absolute inset-0 rounded-md border border-input"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{viewMode !== "edit" && (
|
||||
<div className="prose dark:prose-invert">
|
||||
<MdxPreview source={solution.content} components={{ Accordion, VideoEmbed }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* 标题输入 (仅展示) */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="solution-title">题解标题</Label>
|
||||
<Input
|
||||
id="solution-title"
|
||||
value={solution.title}
|
||||
onChange={(e) =>
|
||||
setSolution({ ...solution, title: e.target.value })
|
||||
}
|
||||
placeholder="输入题解标题"
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="button" onClick={handleSave}>保存更改</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* 编辑/预览切换 */}
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "edit" ? "default" : "outline"}
|
||||
onClick={() => setViewMode("edit")}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "preview" ? "default" : "outline"}
|
||||
onClick={() =>
|
||||
setViewMode(viewMode === "preview" ? "edit" : "preview")
|
||||
}
|
||||
>
|
||||
{viewMode === "preview" ? "取消" : "预览"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={viewMode === "compare" ? "default" : "outline"}
|
||||
onClick={() => setViewMode("compare")}
|
||||
>
|
||||
对比
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 编辑/预览区域 */}
|
||||
<div
|
||||
className={
|
||||
viewMode === "compare"
|
||||
? "grid grid-cols-2 gap-6"
|
||||
: "flex flex-col gap-6"
|
||||
}
|
||||
>
|
||||
{(viewMode === "edit" || viewMode === "compare") && (
|
||||
<div className="relative h-[600px]">
|
||||
<CoreEditor
|
||||
value={solution.content}
|
||||
onChange={(val) =>
|
||||
setSolution({ ...solution, content: val || "" })
|
||||
}
|
||||
language="markdown"
|
||||
className="absolute inset-0 rounded-md border border-input"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{viewMode !== "edit" && (
|
||||
<div className="prose dark:prose-invert">
|
||||
<MdxPreview
|
||||
source={solution.content}
|
||||
components={{ Accordion, VideoEmbed }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button type="button" onClick={handleSave}>
|
||||
保存更改
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
@ -4,9 +4,9 @@ import React, { useState, useEffect } from "react";
|
||||
import { generateAITestcase } from "@/app/actions/ai-testcase";
|
||||
import { getProblemData } from "@/app/actions/getProblem";
|
||||
import {
|
||||
addProblemTestcase,
|
||||
updateProblemTestcase,
|
||||
deleteProblemTestcase,
|
||||
addProblemTestcase,
|
||||
updateProblemTestcase,
|
||||
deleteProblemTestcase,
|
||||
} from "@/components/creater/problem-maintain";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@ -15,210 +15,249 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface Testcase {
|
||||
id: string;
|
||||
expectedOutput: string;
|
||||
inputs: { name: string; value: string }[];
|
||||
id: string;
|
||||
expectedOutput: string;
|
||||
inputs: { name: string; value: string }[];
|
||||
}
|
||||
|
||||
export default function EditTestcasePanel({ problemId }: { problemId: string }) {
|
||||
const [testcases, setTestcases] = useState<Testcase[]>([]);
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
export default function EditTestcasePanel({
|
||||
problemId,
|
||||
}: {
|
||||
problemId: string;
|
||||
}) {
|
||||
const [testcases, setTestcases] = useState<Testcase[]>([]);
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
|
||||
// 加载测试用例
|
||||
useEffect(() => {
|
||||
async function fetch() {
|
||||
try {
|
||||
const data = await getProblemData(problemId);
|
||||
setTestcases(data.testcases || []);
|
||||
} catch (err) {
|
||||
console.error("加载测试用例失败:", err);
|
||||
toast.error("加载测试用例失败");
|
||||
}
|
||||
// 加载测试用例
|
||||
useEffect(() => {
|
||||
async function fetch() {
|
||||
try {
|
||||
const data = await getProblemData(problemId);
|
||||
setTestcases(data.testcases || []);
|
||||
} catch (err) {
|
||||
console.error("加载测试用例失败:", err);
|
||||
toast.error("加载测试用例失败");
|
||||
}
|
||||
}
|
||||
fetch();
|
||||
}, [problemId]);
|
||||
|
||||
// 本地添加测试用例
|
||||
const handleAddTestcase = () =>
|
||||
setTestcases((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: `new-${Date.now()}-${Math.random()}`,
|
||||
expectedOutput: "",
|
||||
inputs: [{ name: "input1", value: "" }],
|
||||
},
|
||||
]);
|
||||
|
||||
// AI 生成测试用例
|
||||
const handleAITestcase = async () => {
|
||||
setIsGenerating(true);
|
||||
try {
|
||||
const ai = await generateAITestcase({ problemId });
|
||||
setTestcases((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: `new-${Date.now()}-${Math.random()}`,
|
||||
expectedOutput: ai.expectedOutput,
|
||||
inputs: ai.inputs,
|
||||
},
|
||||
]);
|
||||
window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error("AI 生成测试用例失败");
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 删除测试用例(本地 + 服务器)
|
||||
const handleRemoveTestcase = async (idx: number) => {
|
||||
const tc = testcases[idx];
|
||||
if (!tc.id.startsWith("new-")) {
|
||||
try {
|
||||
const res = await deleteProblemTestcase(problemId, tc.id);
|
||||
if (res.success) toast.success("删除测试用例成功");
|
||||
else toast.error("删除测试用例失败");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error("删除测试用例异常");
|
||||
}
|
||||
}
|
||||
setTestcases((prev) => prev.filter((_, i) => i !== idx));
|
||||
};
|
||||
|
||||
// 修改预期输出
|
||||
const handleExpectedOutputChange = (idx: number, val: string) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
c[idx] = { ...c[idx], expectedOutput: val };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 修改输入参数
|
||||
const handleInputChange = (
|
||||
tIdx: number,
|
||||
iIdx: number,
|
||||
field: "name" | "value",
|
||||
val: string
|
||||
) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
const newInputs = [...c[tIdx].inputs];
|
||||
newInputs[iIdx] = { ...newInputs[iIdx], [field]: val };
|
||||
c[tIdx] = { ...c[tIdx], inputs: newInputs };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 添加输入参数
|
||||
const handleAddInput = (tIdx: number) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
const inputs = [
|
||||
...c[tIdx].inputs,
|
||||
{ name: `input${c[tIdx].inputs.length + 1}`, value: "" },
|
||||
];
|
||||
c[tIdx] = { ...c[tIdx], inputs };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 删除输入参数
|
||||
const handleRemoveInput = (tIdx: number, iIdx: number) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
const inputs = c[tIdx].inputs.filter((_, i) => i !== iIdx);
|
||||
c[tIdx] = { ...c[tIdx], inputs };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 保存所有测试用例,并刷新最新数据
|
||||
const handleSaveAll = async () => {
|
||||
try {
|
||||
for (let i = 0; i < testcases.length; i++) {
|
||||
const tc = testcases[i];
|
||||
if (
|
||||
tc.expectedOutput.trim() === "" ||
|
||||
tc.inputs.some((inp) => !inp.name.trim() || !inp.value.trim())
|
||||
) {
|
||||
toast.error(`第 ${i + 1} 个测试用例存在空的输入或输出,保存失败`);
|
||||
return;
|
||||
}
|
||||
fetch();
|
||||
}, [problemId]);
|
||||
|
||||
// 本地添加测试用例
|
||||
const handleAddTestcase = () =>
|
||||
setTestcases((prev) => [
|
||||
...prev,
|
||||
{ id: `new-${Date.now()}-${Math.random()}`, expectedOutput: "", inputs: [{ name: "input1", value: "" }] },
|
||||
]);
|
||||
|
||||
// AI 生成测试用例
|
||||
const handleAITestcase = async () => {
|
||||
setIsGenerating(true);
|
||||
try {
|
||||
const ai = await generateAITestcase({ problemId });
|
||||
setTestcases((prev) => [
|
||||
...prev,
|
||||
{ id: `new-${Date.now()}-${Math.random()}`, expectedOutput: ai.expectedOutput, inputs: ai.inputs },
|
||||
]);
|
||||
window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error("AI 生成测试用例失败");
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
if (tc.id.startsWith("new-")) {
|
||||
const res = await addProblemTestcase(
|
||||
problemId,
|
||||
tc.expectedOutput,
|
||||
tc.inputs
|
||||
);
|
||||
if (res.success) {
|
||||
toast.success(`新增测试用例 ${i + 1} 成功`);
|
||||
} else {
|
||||
toast.error(`新增测试用例 ${i + 1} 失败`);
|
||||
}
|
||||
} else {
|
||||
const res = await updateProblemTestcase(
|
||||
problemId,
|
||||
tc.id,
|
||||
tc.expectedOutput,
|
||||
tc.inputs
|
||||
);
|
||||
if (res.success) toast.success(`更新测试用例 ${i + 1} 成功`);
|
||||
else toast.error(`更新测试用例 ${i + 1} 失败`);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 删除测试用例(本地 + 服务器)
|
||||
const handleRemoveTestcase = async (idx: number) => {
|
||||
const tc = testcases[idx];
|
||||
if (!tc.id.startsWith("new-")) {
|
||||
try {
|
||||
const res = await deleteProblemTestcase(problemId, tc.id);
|
||||
if (res.success) toast.success("删除测试用例成功");
|
||||
else toast.error("删除测试用例失败");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error("删除测试用例异常");
|
||||
}
|
||||
}
|
||||
setTestcases((prev) => prev.filter((_, i) => i !== idx));
|
||||
};
|
||||
// 保存完成后刷新最新测试用例
|
||||
const data = await getProblemData(problemId);
|
||||
setTestcases(data.testcases || []);
|
||||
toast.success("测试用例保存并刷新成功");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error("保存测试用例异常");
|
||||
}
|
||||
};
|
||||
|
||||
// 修改预期输出
|
||||
const handleExpectedOutputChange = (idx: number, val: string) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
c[idx] = { ...c[idx], expectedOutput: val };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 修改输入参数
|
||||
const handleInputChange = (
|
||||
tIdx: number,
|
||||
iIdx: number,
|
||||
field: "name" | "value",
|
||||
val: string
|
||||
) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
const newInputs = [...c[tIdx].inputs];
|
||||
newInputs[iIdx] = { ...newInputs[iIdx], [field]: val };
|
||||
c[tIdx] = { ...c[tIdx], inputs: newInputs };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 添加输入参数
|
||||
const handleAddInput = (tIdx: number) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
const inputs = [...c[tIdx].inputs, { name: `input${c[tIdx].inputs.length + 1}`, value: "" }];
|
||||
c[tIdx] = { ...c[tIdx], inputs };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 删除输入参数
|
||||
const handleRemoveInput = (tIdx: number, iIdx: number) =>
|
||||
setTestcases((prev) => {
|
||||
const c = [...prev];
|
||||
const inputs = c[tIdx].inputs.filter((_, i) => i !== iIdx);
|
||||
c[tIdx] = { ...c[tIdx], inputs };
|
||||
return c;
|
||||
});
|
||||
|
||||
// 保存所有测试用例,并刷新最新数据
|
||||
const handleSaveAll = async () => {
|
||||
try {
|
||||
for (let i = 0; i < testcases.length; i++) {
|
||||
const tc = testcases[i];
|
||||
if (tc.expectedOutput.trim() === "" || tc.inputs.some(inp => !inp.name.trim() || !inp.value.trim())) {
|
||||
toast.error(`第 ${i + 1} 个测试用例存在空的输入或输出,保存失败`);
|
||||
return;
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>测试用例</CardTitle>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button onClick={handleAddTestcase}>添加测试用例</Button>
|
||||
<Button onClick={handleAITestcase} disabled={isGenerating}>
|
||||
{isGenerating ? "生成中..." : "使用AI生成测试用例"}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={handleSaveAll}>
|
||||
保存测试用例
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{testcases.map((tc, idx) => (
|
||||
<div key={tc.id} className="border p-4 rounded space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="font-medium">测试用例 {idx + 1}</h3>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => handleRemoveTestcase(idx)}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>预期输出</Label>
|
||||
<Input
|
||||
value={tc.expectedOutput}
|
||||
onChange={(e) =>
|
||||
handleExpectedOutputChange(idx, e.target.value)
|
||||
}
|
||||
|
||||
if (tc.id.startsWith("new-")) {
|
||||
const res = await addProblemTestcase(problemId, tc.expectedOutput, tc.inputs);
|
||||
if (res.success) {
|
||||
toast.success(`新增测试用例 ${i + 1} 成功`);
|
||||
} else {
|
||||
toast.error(`新增测试用例 ${i + 1} 失败`);
|
||||
}
|
||||
} else {
|
||||
const res = await updateProblemTestcase(problemId, tc.id, tc.expectedOutput, tc.inputs);
|
||||
if (res.success) toast.success(`更新测试用例 ${i + 1} 成功`);
|
||||
else toast.error(`更新测试用例 ${i + 1} 失败`);
|
||||
}
|
||||
}
|
||||
|
||||
// 保存完成后刷新最新测试用例
|
||||
const data = await getProblemData(problemId);
|
||||
setTestcases(data.testcases || []);
|
||||
toast.success("测试用例保存并刷新成功");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
toast.error("保存测试用例异常");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader>
|
||||
<CardTitle>测试用例</CardTitle>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button onClick={handleAddTestcase}>添加测试用例</Button>
|
||||
<Button onClick={handleAITestcase} disabled={isGenerating}>
|
||||
{isGenerating ? "生成中..." : "使用AI生成测试用例"}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={handleSaveAll}>
|
||||
保存测试用例
|
||||
placeholder="输入预期输出"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<Label>输入参数</Label>
|
||||
<Button onClick={() => handleAddInput(idx)}>添加输入</Button>
|
||||
</div>
|
||||
{tc.inputs.map((inp, iIdx) => (
|
||||
<div key={iIdx} className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>名称</Label>
|
||||
<Input
|
||||
value={inp.name}
|
||||
onChange={(e) =>
|
||||
handleInputChange(idx, iIdx, "name", e.target.value)
|
||||
}
|
||||
placeholder="参数名称"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>值</Label>
|
||||
<Input
|
||||
value={inp.value}
|
||||
onChange={(e) =>
|
||||
handleInputChange(idx, iIdx, "value", e.target.value)
|
||||
}
|
||||
placeholder="参数值"
|
||||
/>
|
||||
</div>
|
||||
{iIdx > 0 && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleRemoveInput(idx, iIdx)}
|
||||
>
|
||||
删除输入
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{testcases.map((tc, idx) => (
|
||||
<div key={tc.id} className="border p-4 rounded space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="font-medium">测试用例 {idx + 1}</h3>
|
||||
<Button variant="destructive" onClick={() => handleRemoveTestcase(idx)}>
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>预期输出</Label>
|
||||
<Input
|
||||
value={tc.expectedOutput}
|
||||
onChange={(e) => handleExpectedOutputChange(idx, e.target.value)}
|
||||
placeholder="输入预期输出"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<Label>输入参数</Label>
|
||||
<Button onClick={() => handleAddInput(idx)}>添加输入</Button>
|
||||
</div>
|
||||
{tc.inputs.map((inp, iIdx) => (
|
||||
<div key={iIdx} className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>名称</Label>
|
||||
<Input
|
||||
value={inp.name}
|
||||
onChange={(e) => handleInputChange(idx, iIdx, "name", e.target.value)}
|
||||
placeholder="参数名称"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>值</Label>
|
||||
<Input
|
||||
value={inp.value}
|
||||
onChange={(e) => handleInputChange(idx, iIdx, "value", e.target.value)}
|
||||
placeholder="参数值"
|
||||
/>
|
||||
</div>
|
||||
{iIdx > 0 && (
|
||||
<Button variant="outline" onClick={() => handleRemoveInput(idx, iIdx)}>
|
||||
删除输入
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
@ -2,9 +2,23 @@
|
||||
|
||||
import prisma from "@/lib/prisma";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { Difficulty, Locale, ProblemContentType, Language } from "@/generated/client";
|
||||
import {
|
||||
Difficulty,
|
||||
Locale,
|
||||
ProblemContentType,
|
||||
Language,
|
||||
} from "@/generated/client";
|
||||
|
||||
export async function updateProblemDetail(problemId: string, data: { displayId?: number; difficulty?: Difficulty; timeLimit?: number; memoryLimit?: number; isPublished?: boolean }) {
|
||||
export async function updateProblemDetail(
|
||||
problemId: string,
|
||||
data: {
|
||||
displayId?: number;
|
||||
difficulty?: Difficulty;
|
||||
timeLimit?: number;
|
||||
memoryLimit?: number;
|
||||
isPublished?: boolean;
|
||||
}
|
||||
) {
|
||||
try {
|
||||
const updatedProblem = await prisma.problem.update({
|
||||
where: { id: problemId },
|
||||
@ -13,8 +27,8 @@ export async function updateProblemDetail(problemId: string, data: { displayId?:
|
||||
difficulty: data.difficulty,
|
||||
timeLimit: data.timeLimit,
|
||||
memoryLimit: data.memoryLimit,
|
||||
isPublished: data.isPublished
|
||||
}
|
||||
isPublished: data.isPublished,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/problem-editor/${problemId}`);
|
||||
@ -25,25 +39,29 @@ export async function updateProblemDetail(problemId: string, data: { displayId?:
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateProblemDescription(problemId: string, locale: Locale, content: string) {
|
||||
export async function updateProblemDescription(
|
||||
problemId: string,
|
||||
locale: Locale,
|
||||
content: string
|
||||
) {
|
||||
try {
|
||||
const updatedLocalization = await prisma.problemLocalization.upsert({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: problemId,
|
||||
locale: locale,
|
||||
type: ProblemContentType.DESCRIPTION
|
||||
}
|
||||
type: ProblemContentType.DESCRIPTION,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
problemId: problemId,
|
||||
locale: locale,
|
||||
type: ProblemContentType.DESCRIPTION,
|
||||
content: content
|
||||
content: content,
|
||||
},
|
||||
update: {
|
||||
content: content
|
||||
}
|
||||
content: content,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/problem-editor/${problemId}`);
|
||||
@ -54,25 +72,29 @@ export async function updateProblemDescription(problemId: string, locale: Locale
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateProblemSolution(problemId: string, locale: Locale, content: string) {
|
||||
export async function updateProblemSolution(
|
||||
problemId: string,
|
||||
locale: Locale,
|
||||
content: string
|
||||
) {
|
||||
try {
|
||||
const updatedLocalization = await prisma.problemLocalization.upsert({
|
||||
where: {
|
||||
problemId_locale_type: {
|
||||
problemId: problemId,
|
||||
locale: locale,
|
||||
type: ProblemContentType.SOLUTION
|
||||
}
|
||||
type: ProblemContentType.SOLUTION,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
problemId: problemId,
|
||||
locale: locale,
|
||||
type: ProblemContentType.SOLUTION,
|
||||
content: content
|
||||
content: content,
|
||||
},
|
||||
update: {
|
||||
content: content
|
||||
}
|
||||
content: content,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/problem-editor/${problemId}`);
|
||||
@ -83,23 +105,27 @@ export async function updateProblemSolution(problemId: string, locale: Locale, c
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateProblemTemplate(problemId: string, language: Language, content: string) {
|
||||
export async function updateProblemTemplate(
|
||||
problemId: string,
|
||||
language: Language,
|
||||
content: string
|
||||
) {
|
||||
try {
|
||||
const updatedTemplate = await prisma.template.upsert({
|
||||
where: {
|
||||
problemId_language: {
|
||||
problemId: problemId,
|
||||
language: language
|
||||
}
|
||||
language: language,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
problemId: problemId,
|
||||
language: language,
|
||||
content: content
|
||||
content: content,
|
||||
},
|
||||
update: {
|
||||
content: content
|
||||
}
|
||||
content: content,
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/problem-editor/${problemId}`);
|
||||
@ -110,19 +136,24 @@ export async function updateProblemTemplate(problemId: string, language: Languag
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateProblemTestcase(problemId: string, testcaseId: string, expectedOutput: string, inputs: { name: string; value: string }[]) {
|
||||
export async function updateProblemTestcase(
|
||||
problemId: string,
|
||||
testcaseId: string,
|
||||
expectedOutput: string,
|
||||
inputs: { name: string; value: string }[]
|
||||
) {
|
||||
try {
|
||||
// Update testcase
|
||||
const updatedTestcase = await prisma.testcase.update({
|
||||
where: { id: testcaseId },
|
||||
data: {
|
||||
expectedOutput: expectedOutput
|
||||
}
|
||||
expectedOutput: expectedOutput,
|
||||
},
|
||||
});
|
||||
|
||||
// Delete old inputs
|
||||
await prisma.testcaseInput.deleteMany({
|
||||
where: { testcaseId: testcaseId }
|
||||
where: { testcaseId: testcaseId },
|
||||
});
|
||||
|
||||
// Create new inputs
|
||||
@ -131,15 +162,15 @@ export async function updateProblemTestcase(problemId: string, testcaseId: strin
|
||||
testcaseId: testcaseId,
|
||||
index: index,
|
||||
name: input.name,
|
||||
value: input.value
|
||||
}))
|
||||
value: input.value,
|
||||
})),
|
||||
});
|
||||
|
||||
revalidatePath(`/problem-editor/${problemId}`);
|
||||
return {
|
||||
success: true,
|
||||
return {
|
||||
success: true,
|
||||
testcase: updatedTestcase,
|
||||
inputs: createdInputs
|
||||
inputs: createdInputs,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Failed to update problem testcase:", error);
|
||||
@ -147,14 +178,18 @@ export async function updateProblemTestcase(problemId: string, testcaseId: strin
|
||||
}
|
||||
}
|
||||
|
||||
export async function addProblemTestcase(problemId: string, expectedOutput: string, inputs: { name: string; value: string }[]) {
|
||||
export async function addProblemTestcase(
|
||||
problemId: string,
|
||||
expectedOutput: string,
|
||||
inputs: { name: string; value: string }[]
|
||||
) {
|
||||
try {
|
||||
// Create testcase
|
||||
const newTestcase = await prisma.testcase.create({
|
||||
data: {
|
||||
problemId: problemId,
|
||||
expectedOutput: expectedOutput
|
||||
}
|
||||
expectedOutput: expectedOutput,
|
||||
},
|
||||
});
|
||||
|
||||
// Create inputs
|
||||
@ -163,15 +198,15 @@ export async function addProblemTestcase(problemId: string, expectedOutput: stri
|
||||
testcaseId: newTestcase.id,
|
||||
index: index,
|
||||
name: input.name,
|
||||
value: input.value
|
||||
}))
|
||||
value: input.value,
|
||||
})),
|
||||
});
|
||||
|
||||
revalidatePath(`/problem-editor/${problemId}`);
|
||||
return {
|
||||
success: true,
|
||||
return {
|
||||
success: true,
|
||||
testcase: newTestcase,
|
||||
inputs: createdInputs
|
||||
inputs: createdInputs,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Failed to add problem testcase:", error);
|
||||
@ -179,10 +214,13 @@ export async function addProblemTestcase(problemId: string, expectedOutput: stri
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteProblemTestcase(problemId: string, testcaseId: string) {
|
||||
export async function deleteProblemTestcase(
|
||||
problemId: string,
|
||||
testcaseId: string
|
||||
) {
|
||||
try {
|
||||
const deletedTestcase = await prisma.testcase.delete({
|
||||
where: { id: testcaseId }
|
||||
where: { id: testcaseId },
|
||||
});
|
||||
|
||||
revalidatePath(`/problem-editor/${problemId}`);
|
||||
@ -197,9 +235,9 @@ export async function deleteProblemTestcase(problemId: string, testcaseId: strin
|
||||
* 更新题目标题(TITLE)
|
||||
*/
|
||||
export async function updateProblemTitle(
|
||||
problemId: string,
|
||||
locale: Locale,
|
||||
title: string
|
||||
problemId: string,
|
||||
locale: Locale,
|
||||
title: string
|
||||
) {
|
||||
try {
|
||||
const updated = await prisma.problemLocalization.upsert({
|
||||
@ -227,4 +265,4 @@ export async function updateProblemTitle(
|
||||
console.error("更新题目标题失败:", error);
|
||||
return { success: false, error: "更新题目标题失败" };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,18 +2,18 @@ import { z } from "zod";
|
||||
|
||||
// 优化代码的输入类型
|
||||
export const OptimizeCodeInputSchema = z.object({
|
||||
code: z.string(), // 用户输入的代码
|
||||
error: z.string().optional(), // 可选的错误信息
|
||||
problemId: z.string().optional(), // 可选的题目ID
|
||||
code: z.string(), // 用户输入的代码
|
||||
error: z.string().optional(), // 可选的错误信息
|
||||
problemId: z.string().optional(), // 可选的题目ID
|
||||
});
|
||||
|
||||
export type OptimizeCodeInput = z.infer<typeof OptimizeCodeInputSchema>;
|
||||
|
||||
// 优化代码的输出类型
|
||||
export const OptimizeCodeOutputSchema = z.object({
|
||||
optimizedCode: z.string(), // 优化后的代码
|
||||
explanation: z.string(), // 优化说明
|
||||
issuesFixed: z.array(z.string()).optional(), // 修复的问题列表
|
||||
optimizedCode: z.string(), // 优化后的代码
|
||||
explanation: z.string(), // 优化说明
|
||||
issuesFixed: z.array(z.string()).optional(), // 修复的问题列表
|
||||
});
|
||||
|
||||
export type OptimizeCodeOutput = z.infer<typeof OptimizeCodeOutputSchema>;
|
||||
export type OptimizeCodeOutput = z.infer<typeof OptimizeCodeOutputSchema>;
|
||||
|
@ -1,21 +1,19 @@
|
||||
import {z} from "zod";
|
||||
import { z } from "zod";
|
||||
|
||||
export const AITestCaseInputSchema = z.object({
|
||||
problemId: z.string(),
|
||||
})
|
||||
problemId: z.string(),
|
||||
});
|
||||
|
||||
export type AITestCaseInput = z.infer<typeof AITestCaseInputSchema>
|
||||
export type AITestCaseInput = z.infer<typeof AITestCaseInputSchema>;
|
||||
|
||||
const input = z.object({
|
||||
name: z.string(),
|
||||
value: z.string()
|
||||
})
|
||||
name: z.string(),
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
export const AITestCaseOutputSchema = z.object({
|
||||
expectedOutput: z.string(),
|
||||
inputs: z.array(input)
|
||||
})
|
||||
|
||||
export type AITestCaseOutput = z.infer<typeof AITestCaseOutputSchema>
|
||||
|
||||
expectedOutput: z.string(),
|
||||
inputs: z.array(input),
|
||||
});
|
||||
|
||||
export type AITestCaseOutput = z.infer<typeof AITestCaseOutputSchema>;
|
||||
|
Loading…
Reference in New Issue
Block a user