Compare commits

..
7 Commits
Author SHA1 Message Date
wonder 8e4b0e4060 ✨Feat: 完成前端工程场景 2026-03-29 10:10:32 +08:00
wonder 51e71da224 ✨Feat: 完成前端测试问答 2026-03-29 09:37:25 +08:00
wonder dd8cd97cc5 🔧Chore: 清除测试 2026-03-28 20:01:22 +08:00
wonder 45c668e970 ♻️Refactor: 清除 mermaid 2026-03-28 20:00:08 +08:00
wonder 06a4486a4f ✨Feat: 分 Tab 加载展示 2026-03-28 18:47:05 +08:00
wonder 9cf9321b1d ✨Feat: Mermaid 图表组件 2026-03-28 18:03:46 +08:00
wonder 9cd8345004 ✨Feat: 优化布局 加入文本框和按钮 2026-03-28 15:08:05 +08:00
15 changed files with 755 additions and 159 deletions
+8 -4
View File
@@ -44,7 +44,7 @@ func CallWithMessage(llm llms.Model, ctx context.Context, prompt string) (respon
return response return response
} }
func CallWithAgent(llm llms.Model, ctx context.Context, topic string, promptPath string,) (response string) { func CallWithAgent(llm llms.Model, ctx context.Context, topic string, promptPath string) (response string) {
content, err := os.ReadFile(promptPath) content, err := os.ReadFile(promptPath)
if err != nil { if err != nil {
fmt.Printf("File err: %v", err) fmt.Printf("File err: %v", err)
@@ -100,18 +100,20 @@ func CallWithAgentDefined[T any](llm llms.Model, ctx context.Context, topic stri
"用户正在学习Go语言和React框架,你是用户的助手。\n"+prompt, "用户正在学习Go语言和React框架,你是用户的助手。\n"+prompt,
) )
fmt.Printf("Raw output: %v\n\n", responseString)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
responseString = strings.TrimPrefix(responseString, "\n")
responseString = strings.TrimSuffix(responseString, "\n")
if !strings.Contains(responseString, "```json") { if !strings.Contains(responseString, "```json") {
responseString = "```json\n" + responseString + "```" responseString = "```json\n" + responseString + "\n```"
} }
fmt.Printf("AI: %s\n\n",responseString) // fmt.Printf("AI: %s\n\n", responseString)
response, err = parse.Parse(responseString) response, err = parse.Parse(responseString)
if err != nil { if err != nil {
@@ -119,5 +121,7 @@ func CallWithAgentDefined[T any](llm llms.Model, ctx context.Context, topic stri
return return
} }
fmt.Printf("API:\n%v", response)
return response return response
} }
+4 -11
View File
@@ -11,7 +11,6 @@ import (
var files = []string{ var files = []string{
".\\prompt\\card.txt", ".\\prompt\\card.txt",
".\\prompt\\guodegang.txt", ".\\prompt\\guodegang.txt",
".\\prompt\\mermaid.txt",
".\\prompt\\quiz.txt", ".\\prompt\\quiz.txt",
".\\prompt\\scenario.txt", ".\\prompt\\scenario.txt",
} }
@@ -28,20 +27,14 @@ func GetGuodegang(llm llms.Model, ctx context.Context, topic string) (response r
return return
} }
func GetMermaid(llm llms.Model, ctx context.Context, topic string) (response response_struct.Mermaid) {
file := files[2]
response = agent.CallWithAgentDefined(llm, ctx, topic, file, response_struct.Mermaid{})
return
}
func GetQuiz(llm llms.Model, ctx context.Context, topic string) (response response_struct.Quiz) { func GetQuiz(llm llms.Model, ctx context.Context, topic string) (response response_struct.Quiz) {
file := files[3] file := files[2]
response = agent.CallWithAgentDefined(llm, ctx, topic, file, response_struct.Quiz{}) response = agent.CallWithAgentDefined(llm, ctx, topic, file, response_struct.Quiz{})
return return
} }
func GetScenario(llm llms.Model, ctx context.Context, topic string) (response response_struct.Scenario) { func GetScenario(llm llms.Model, ctx context.Context, topic string) (response response_struct.ScenarioResponse) {
file := files[4] file := files[3]
response = agent.CallWithAgentDefined(llm, ctx, topic, file, response_struct.Scenario{}) response = agent.CallWithAgentDefined(llm, ctx, topic, file, response_struct.ScenarioResponse{})
return return
} }
-8
View File
@@ -69,13 +69,6 @@ func main() {
"message": message, "message": message,
}) })
}) })
route.GET("/mermaid/:topic", func(c *gin.Context) {
topic := c.Param("topic")
message := handle.GetMermaid(llm, ctx, topic)
c.JSON(200, gin.H{
"message": message,
})
})
route.GET("/quiz/:topic", func(c *gin.Context) { route.GET("/quiz/:topic", func(c *gin.Context) {
topic := c.Param("topic") topic := c.Param("topic")
message := handle.GetQuiz(llm, ctx, topic) message := handle.GetQuiz(llm, ctx, topic)
@@ -93,5 +86,4 @@ func main() {
route.Run() route.Run()
} }
-6
View File
@@ -1,6 +0,0 @@
请为"{{.Knowledge}}"生成一个Mermaid思维导图或流程图,要求:
1. 零未定义节点:所有节点(A[文本]、B(文本)等)必须在关系语句前先定义。
2. 严格缩进与换行:使用2个空格缩进,每条关系语句独立成行。
3. 括号与引号成对:所有()、[]、<>、""必须严格配对,无多余空格。
4. 箭头方向明确:使用标准箭头 -->、---、-.-> 等,禁止使用 ->(不完整)或 =>(错误)。
5. 避免中文直接嵌入:若需中文,确保用双引号包裹(如 A["开始"]),或建议用户使用英文标签。
+1
View File
@@ -3,3 +3,4 @@
2. 难度分布:5道基础题、5道中级题、5道进阶题 2. 难度分布:5道基础题、5道中级题、5道进阶题
3. 每道题都要提供详细的解析说明 3. 每道题都要提供详细的解析说明
4. 选项之间要有明显的区别,避免模棱两可 4. 选项之间要有明显的区别,避免模棱两可
5. 输出选项不需要提供 ABCD 字母
-9
View File
@@ -1,9 +0,0 @@
package response_struct
type AllStruct struct {
CardStruct Card `json:"card"`
GuodegangStruct Guodegang `json:"guodegang"`
MermaidStruct Mermaid `json:"mermaid"`
QuizStruct Quiz `json:"quiz"`
ScenarioStruct Scenario `json:"scenario"`
}
-6
View File
@@ -1,6 +0,0 @@
package response_struct
type Mermaid struct {
Type string `json:"type"`
Content string `json:"content"`
}
+1 -12
View File
@@ -28,17 +28,6 @@ func TestGuodegang(t *testing.T) {
t.Log(output) t.Log(output)
} }
func TestMermaid(t *testing.T) {
definedMermaid, err := outputparser.NewDefined(Mermaid{})
if err != nil {
t.Fatalf("%v", err)
}
output := definedMermaid.GetFormatInstructions()
t.Log(output)
}
func TestQuiz(t *testing.T) { func TestQuiz(t *testing.T) {
definedQuiz, err := outputparser.NewDefined(Quiz{}) definedQuiz, err := outputparser.NewDefined(Quiz{})
@@ -51,7 +40,7 @@ func TestQuiz(t *testing.T) {
} }
func TestScenario(t *testing.T) { func TestScenario(t *testing.T) {
definedScenario, err := outputparser.NewDefined(Scenario{}) definedScenario, err := outputparser.NewDefined(ScenarioResponse{})
if err != nil { if err != nil {
t.Fatalf("%v", err) t.Fatalf("%v", err)
-26
View File
@@ -1,26 +0,0 @@
package utils
import (
"encoding/json"
"fmt"
"github.com/tmc/langchaingo/outputparser"
)
// Parse parses the output of an LLM call.
func (p outputparser.Defined[T)(T) Parse(text string) (T, error) {
var target T
// Removes '```json' and '```' from the start and end of the text.
const opening = "```json"
const closing = "```"
if text[:len(opening)] != opening || text[len(text)-len(closing):] != closing {
return target, nil
// return target, fmt.Errorf("input text should start with %s and end with %s", opening, closing)
}
parseableJSON := text[len(opening) : len(text)-len(closing)]
if err := json.Unmarshal([]byte(parseableJSON), &target); err != nil {
return target, fmt.Errorf("could not parse generated JSON: %w", err)
}
return target, nil
}
+171 -10
View File
@@ -1,18 +1,179 @@
import { useState } from "react";
import { ProgressBar, Label, Tabs } from "@heroui/react";
import Card from "./components/Card"; import Card from "./components/Card";
import Guodegang from "./components/Guodegang"; import Guodegang from "./components/Guodegang";
import { Surface } from "@heroui/react"; import Quiz from "./components/Quiz";
import Topic from "./components/Topic";
import Scenario from "./components/Scenario";
/* eslint-disable @typescript-eslint/no-explicit-any */
function App() { function App() {
const [topic, setTopic] = useState('');
const [cardData, setCardData]: any = useState(null);
const [cardLoading, setCardLoading] = useState(false);
const [cardError, setCardError] = useState<string | null>(null);
const [guodegangData, setGuodegangData]: any = useState(null);
const [guodegangLoading, setGuodegangLoading] = useState(false);
const [guodegangError, setGuodegangError] = useState<string | null>(null);
const [quizData, setQuizData]: any = useState(null);
const [quizLoading, setQuizLoading] = useState(false);
const [quizError, setQuizError] = useState<string | null>(null);
const [scenarioData, setScenarioData]: any = useState(null);
const [scenarioLoading, setScenarioLoading] = useState(false);
const [scenarioError, setScenarioError] = useState<string | null>(null);
const fetchData = async (topicToFetch: string) => {
setCardLoading(true);
setGuodegangLoading(true);
setQuizLoading(true);
setScenarioLoading(true);
setCardError(null);
setGuodegangError(null);
setQuizError(null);
setScenarioError(null);
const cardUrl = `http://localhost:8080/card/${encodeURIComponent(topicToFetch)}`;
const guodegangUrl = `http://localhost:8080/guodegang/${encodeURIComponent(topicToFetch)}`;
const quizUrl = `http://localhost:8080/quiz/${encodeURIComponent(topicToFetch)}`;
const scenarioUrl = `http://localhost:8080/scenario/${encodeURIComponent(topicToFetch)}`;
const abortController = new AbortController();
const timeoutId = setTimeout(() => abortController.abort(), 300000);
const fetchCard = async () => {
try {
const response = await fetch(cardUrl, { signal: abortController.signal });
if (!response.ok) throw new Error(`Card API failed: ${response.status}`);
const result = await response.json();
setCardData(result.message);
} catch (error) {
console.error("Error fetching card data:", error);
setCardError("Failed to load card data");
} finally {
setCardLoading(false);
}
};
const fetchGuodegang = async () => {
try {
const response = await fetch(guodegangUrl, { signal: abortController.signal });
if (!response.ok) throw new Error(`Guodegang API failed: ${response.status}`);
const result = await response.json();
setGuodegangData(result.message);
} catch (error) {
console.error("Error fetching guodegang data:", error);
setGuodegangError("Failed to load guodegang data");
} finally {
setGuodegangLoading(false);
}
};
const fetchQuiz = async () => {
try {
const response = await fetch(quizUrl, { signal: abortController.signal });
if (!response.ok) throw new Error(`Quiz API failed: ${response.status}`);
const result = await response.json();
setQuizData(result.message);
} catch (error) {
console.error("Error fetching quiz data:", error);
setQuizError("Failed to load quiz data");
} finally {
setQuizLoading(false);
}
};
const fetchScenario = async () => {
try {
const response = await fetch(scenarioUrl, { signal: abortController.signal });
if (!response.ok) throw new Error(`Scenario API failed: ${response.status}`);
const result = await response.json();
setScenarioData(result.message);
} catch (error) {
console.error("Error fetching scenario data:", error);
setScenarioError("Failed to load scenario data");
} finally {
setScenarioLoading(false);
}
};
Promise.allSettled([fetchCard(), fetchGuodegang(), fetchQuiz(), fetchScenario()]).finally(() => {
clearTimeout(timeoutId);
});
};
const handleTopicSubmit = (newTopic: string) => {
setTopic(newTopic);
if (newTopic) {
fetchData(newTopic);
}
};
const cardLoaded = !cardLoading && !!cardData;
const guodegangLoaded = !guodegangLoading && !!guodegangData;
const quizLoaded = !quizLoading && !!quizData;
const scenarioLoaded = !scenarioLoading && !!scenarioData;
const progress = (() => {
if (!topic) return 0;
const loadedCount = [cardLoaded, guodegangLoaded, quizLoaded, scenarioLoaded].filter(Boolean).length;
return Math.round((loadedCount / 4) * 100);
})();
return ( return (
<> <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '20px' }}>
<Surface <Topic onTopicSubmit={handleTopicSubmit}/>
className="flex min-w-[320px] flex-row gap-4 rounded-3xl p-6 flex-wrap justify-center" {topic && (
variant="default" <div className="w-64">
> <ProgressBar value={progress} color="accent">
<Card topic="React Hooks" /> <Label>Data Loading</Label>
<Guodegang topic="React Hooks" /> <ProgressBar.Output />
</Surface> <ProgressBar.Track>
</> <ProgressBar.Fill />
</ProgressBar.Track>
</ProgressBar>
</div>
)}
<div className="w-full max-w-8xl">
<Tabs className="w-full">
<Tabs.ListContainer>
<Tabs.List aria-label="View options">
<Tabs.Tab id="card">
<Tabs.Separator />
<Tabs.Indicator />
📚 学习卡片
</Tabs.Tab>
<Tabs.Tab id="guodegang">
<Tabs.Separator />
<Tabs.Indicator />
🎭 德云社讲解
</Tabs.Tab>
<Tabs.Tab id="quiz">
<Tabs.Separator />
<Tabs.Indicator />
📝 测验问答
</Tabs.Tab>
<Tabs.Tab id="scenario">
<Tabs.Separator />
<Tabs.Indicator />
💡 工程场景
</Tabs.Tab>
</Tabs.List>
</Tabs.ListContainer>
<Tabs.Panel id="card">
<Card topic={topic} data={cardData} loading={cardLoading} error={cardError} />
</Tabs.Panel>
<Tabs.Panel id="guodegang">
<Guodegang topic={topic} data={guodegangData} loading={guodegangLoading} error={guodegangError} />
</Tabs.Panel>
<Tabs.Panel id="quiz">
<Quiz topic={topic} data={quizData} loading={quizLoading} error={quizError} />
</Tabs.Panel>
<Tabs.Panel id="scenario">
<Scenario topic={topic} data={scenarioData} loading={scenarioLoading} error={scenarioError} />
</Tabs.Panel>
</Tabs>
</div>
</div>
); );
} }
+23 -30
View File
@@ -1,5 +1,4 @@
import { Card } from "@heroui/react"; import { Card } from "@heroui/react";
import { useEffect, useState } from "react";
interface KeyPointItem { interface KeyPointItem {
point: string; point: string;
@@ -51,35 +50,12 @@ interface CardData {
interface Props { interface Props {
topic: string; topic: string;
data: CardData | null;
loading: boolean;
error: string | null;
} }
export default function Default({ topic }: Props) { export default function Default({ topic, data, loading, error }: Props) {
const [data, setData] = useState<CardData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(
`http://localhost:8080/card/${encodeURIComponent(topic)}`,
);
if (!response.ok) {
throw new Error("API Error");
}
const result = await response.json();
setData(result.message);
setError(null);
} catch (error) {
console.error("Failed to fetch data: ", error);
setError("Failed to load data. Please try again.");
} finally {
setLoading(false);
}
};
fetchData();
}, [topic]);
if (loading) { if (loading) {
return ( return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto"> <div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
@@ -100,6 +76,23 @@ export default function Default({ topic }: Props) {
); );
} }
if (!topic || !data) {
return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 p-8">
<div className="absolute upper-0 right-0 -mr-2 -mb-2 pointer-events-none select-none">
<span className="text-[10rem] opacity-80 blur-none">🧐</span>
</div>
<div className="text-center text-gray-600">
<div className="text-3xl mb-4">📚</div>
<div className="text-lg font-medium mb-2">学习卡片组件</div>
<div className="text-sm text-gray-500">输入主题后,这里将展示相关的核心知识点、常见误解和最佳实践</div>
</div>
</Card>
</div>
);
}
return ( return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto"> <div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100"> <Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100">
@@ -118,7 +111,7 @@ export default function Default({ topic }: Props) {
)} )}
</div> </div>
<Card.Description className="px-6 pb-6 space-y-6"> <div className="px-6 pb-6 space-y-6">
<div> <div>
<h3 className="flex items-center text-lg font-semibold text-gray-700 mb-3"> <h3 className="flex items-center text-lg font-semibold text-gray-700 mb-3">
<span className="mr-2"></span> <span className="mr-2"></span>
@@ -232,7 +225,7 @@ export default function Default({ topic }: Props) {
{data!.mnemonic.content} {data!.mnemonic.content}
</p> </p>
</div> </div>
</Card.Description> </div>
</div> </div>
</Card> </Card>
</div> </div>
+23 -32
View File
@@ -1,5 +1,4 @@
import { Card } from "@heroui/react"; import { Card } from "@heroui/react";
import { useEffect, useState } from "react";
interface GuodegangData { interface GuodegangData {
name: string; name: string;
@@ -8,35 +7,12 @@ interface GuodegangData {
interface Props { interface Props {
topic: string; topic: string;
data: GuodegangData | null;
loading: boolean;
error: string | null;
} }
export default function Guodegang({ topic }: Props) { export default function Guodegang({ topic, data, loading, error }: Props) {
const [data, setData] = useState<GuodegangData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(
`http://localhost:8080/guodegang/${encodeURIComponent(topic)}`,
);
if (!response.ok) {
throw new Error("API Error");
}
const result = await response.json();
setData(result.message);
setError(null);
} catch (error) {
console.error("Failed to fetch data: ", error);
setError("Failed to load data. Please try again.");
} finally {
setLoading(false);
}
};
fetchData();
}, [topic]);
if (loading) { if (loading) {
return ( return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto"> <div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
@@ -57,6 +33,23 @@ export default function Guodegang({ topic }: Props) {
); );
} }
if (!topic || !data) {
return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 p-8">
<div className="absolute upper-0 right-0 -mr-2 -mb-2 pointer-events-none select-none">
<span className="text-[10rem] opacity-80 blur-none">🎤</span>
</div>
<div className="text-center text-gray-600">
<div className="text-3xl mb-4">🎭</div>
<div className="text-lg font-medium mb-2">德云社风格讲解</div>
<div className="text-sm text-gray-500">输入主题后,这里将用相声的生动语言为您讲解知识点</div>
</div>
</Card>
</div>
);
}
return ( return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto"> <div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100"> <Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100">
@@ -72,10 +65,8 @@ export default function Guodegang({ topic }: Props) {
<div className="h-1 w-20 bg-gradient-to-r from-yellow-500 to-orange-500 rounded"></div> <div className="h-1 w-20 bg-gradient-to-r from-yellow-500 to-orange-500 rounded"></div>
</div> </div>
<Card.Description className="px-6 pb-6"> <Card.Description className="px-6 pb-6 text-gray-700 leading-relaxed whitespace-pre-line">
<p className="text-gray-700 leading-relaxed whitespace-pre-line"> {data!.content}
{data!.content}
</p>
</Card.Description> </Card.Description>
</div> </div>
</Card> </Card>
+279
View File
@@ -0,0 +1,279 @@
import { Button } from "@heroui/react";
import { useState, useMemo } from "react";
interface Questions {
question: string;
options: string[];
answer: string;
explanation: string;
}
interface QuizData {
questions: Questions[];
}
interface Props {
topic: string;
data: QuizData | null;
loading: boolean;
error: string | null;
}
interface UserAnswer {
selected: string;
correct: boolean;
}
export default function Quiz({ topic, data, loading, error }: Props) {
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
const [selectedOption, setSelectedOption] = useState<string | null>(null);
const [isAnswerSubmitted, setIsAnswerSubmitted] = useState(false);
const [userAnswers, setUserAnswers] = useState<Map<number, UserAnswer>>(new Map());
const [quizComplete, setQuizComplete] = useState(false);
const currentQuestion = data?.questions?.[currentQuestionIndex];
const isLastQuestion = data?.questions ? currentQuestionIndex === data.questions.length - 1 : false;
const correctCount = useMemo(() => {
return Array.from(userAnswers.values()).filter(a => a.correct).length;
}, [userAnswers]);
const handleOptionSelect = (option: string) => {
if (!isAnswerSubmitted) {
setSelectedOption(option);
}
};
const handleSubmit = () => {
if (selectedOption && currentQuestion) {
const isCorrect = selectedOption === currentQuestion.answer;
setUserAnswers(new Map(userAnswers).set(currentQuestionIndex, {
selected: selectedOption,
correct: isCorrect
}));
setIsAnswerSubmitted(true);
}
};
const handleNext = () => {
if (isLastQuestion) {
setQuizComplete(true);
} else {
setCurrentQuestionIndex(prev => prev + 1);
setSelectedOption(null);
setIsAnswerSubmitted(false);
}
};
const handleRetry = () => {
setCurrentQuestionIndex(0);
setSelectedOption(null);
setIsAnswerSubmitted(false);
setUserAnswers(new Map());
setQuizComplete(false);
};
if (loading) {
return (
<div className="w-full max-w-4xl mx-auto p-6">
<div className="text-center text-gray-600 text-lg">Loading quiz...</div>
</div>
);
}
if (error) {
return (
<div className="w-full max-w-4xl mx-auto p-6">
<div className="text-center text-red-600 text-lg">{error}</div>
</div>
);
}
if (!data || data.questions.length === 0) {
return (
<div className="w-full max-w-4xl mx-auto p-6">
<div className="text-center text-gray-600">
<div className="text-5xl mb-4">📝</div>
<div className="text-xl font-medium mb-2">测验问答</div>
<div className="text-sm text-gray-500">输入主题后,这里将显示相关的测验题目</div>
</div>
</div>
);
}
if (quizComplete) {
const percentage = Math.round((correctCount / data.questions.length) * 100);
return (
<div className="w-full max-w-4xl mx-auto p-6 space-y-8">
<div>
<h2 className="text-3xl font-bold text-center text-gray-800 mb-2">{topic} - Quiz Complete!</h2>
<div className="h-1 w-32 mx-auto bg-gradient-to-r from-blue-500 to-indigo-500 rounded"></div>
</div>
<div className="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-2xl p-8 border border-blue-200">
<div className="text-center">
<div className="text-6xl mb-4">{percentage >= 60 ? '🎉' : percentage >= 40 ? '👍' : '💪'}</div>
<div className="text-5xl font-bold text-gray-800 mb-4">
{correctCount} / {data.questions.length}
</div>
<div className="text-2xl font-semibold text-gray-600 mb-2">
{percentage}%
</div>
<p className="text-gray-500">
{percentage >= 80 ? 'Excellent!' : percentage >= 60 ? 'Good job!' : 'Keep practicing!'}
</p>
</div>
</div>
<div className="space-y-4">
<h3 className="text-xl font-semibold text-gray-800 mb-4">Review Your Answers</h3>
{data.questions.map((question, index) => {
const userAnswer = userAnswers.get(index);
const isCorrect = userAnswer?.correct ?? false;
const userSelected = userAnswer?.selected;
return (
<div key={index} className={`p-6 rounded-xl border-2 ${isCorrect ? 'border-green-300 bg-green-50' : 'border-red-300 bg-red-50'}`}>
<div className="flex items-start gap-3 mb-4">
<span className={`text-2xl ${isCorrect ? 'text-green-500' : 'text-red-500'}`}>
{isCorrect ? '✓' : '✗'}
</span>
<div className="flex-1">
<p className="font-medium text-gray-800 mb-2">Question {index + 1}: {question.question}</p>
<div className="space-y-2 text-sm">
<div className={isCorrect ? 'text-green-600' : 'text-red-700'}>
Your answer: <span className="font-medium">{userSelected}</span>
{!isCorrect && (
<span className="ml-2 text-green-600 font-medium">(Correct: {question.answer})</span>
)}
</div>
</div>
<div className="mt-3 p-3 bg-white rounded-lg text-sm text-gray-700">
<span className="font-medium">Explanation:</span> {question.explanation}
</div>
</div>
</div>
</div>
);
})}
</div>
<div className="flex justify-center">
<Button variant="primary" size="lg" onPress={handleRetry}>
Try Again 🔄
</Button>
</div>
</div>
);
}
if (!currentQuestion) {
return null;
}
const isCorrect = selectedOption === currentQuestion.answer;
return (
<div className="w-full max-w-4xl mx-auto p-6 space-y-8">
<div>
<div className="flex justify-between items-center mb-2">
<h2 className="text-2xl font-bold text-gray-800">{topic}</h2>
<span className="text-sm text-gray-500 font-medium">
Question {currentQuestionIndex + 1} of {data.questions.length}
</span>
</div>
<div className="h-1 w-full bg-gray-200 rounded-full overflow-hidden">
<div
className="h-full bg-gradient-to-r from-blue-500 to-indigo-500 transition-all duration-300"
style={{ width: `${((currentQuestionIndex + 1) / data.questions.length) * 100}%` }}
/>
</div>
</div>
<div className="space-y-8">
<h2 className="text-2xl font-semibold text-center text-gray-800 leading-relaxed">
{currentQuestion.question}
</h2>
<div className="grid grid-cols-4 gap-4">
{currentQuestion.options.map((option, index) => {
const letter = String.fromCharCode(65 + index);
const isSelected = selectedOption === option;
const isCorrectOption = isAnswerSubmitted && option === currentQuestion.answer;
const isWrongUserAnswer = isAnswerSubmitted && isSelected && option !== currentQuestion.answer;
return (
<button
key={index}
onClick={() => handleOptionSelect(option)}
disabled={isAnswerSubmitted}
className={`
p-6 rounded-xl border-2 transition-all duration-200
${isAnswerSubmitted
? isCorrectOption
? 'border-green-500 bg-green-50'
: isWrongUserAnswer
? 'border-red-500 bg-red-50 opacity-60'
: 'border-gray-200 opacity-60'
: isSelected
? 'border-blue-500 bg-blue-50 shadow-md'
: 'border-gray-200 hover:border-blue-400 hover:bg-blue-50'
}
`}
>
<div className="text-center space-y-2">
<div className={`font-bold text-lg ${isCorrectOption ? 'text-green-600' : isWrongUserAnswer ? 'text-red-600' : 'text-gray-800'}`}>
{letter}.
</div>
<div className={`text-sm font-medium ${isCorrectOption ? 'text-green-700' : isWrongUserAnswer ? 'text-gray-600' : 'text-gray-700'}`}>
{option}
</div>
{isCorrectOption && !isWrongUserAnswer && (
<div className="text-green-600 font-bold">✓</div>
)}
</div>
</button>
);
})}
</div>
{!isAnswerSubmitted ? (
<div className="flex justify-center">
<Button
variant="primary"
size="lg"
isDisabled={!selectedOption}
onPress={handleSubmit}
className="min-w-[150px]"
>
Submit
</Button>
</div>
) : (
<div className="flex flex-col items-center space-y-4">
<div className={`${isCorrect ? 'text-green-600' : 'text-red-600'} text-xl font-semibold`}>
{isCorrect ? '✓ Correct!' : '✗ Incorrect. Correct answer is ' + currentQuestion.answer}
</div>
<div className="w-full mt-6 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl border border-blue-200 p-6">
<h3 className="font-bold text-gray-800 mb-2 text-lg">Explanation:</h3>
<p className="text-gray-700 leading-relaxed">{currentQuestion.explanation}</p>
</div>
<div className="flex justify-center mt-4">
<Button
variant="primary"
size="lg"
onPress={handleNext}
className="min-w-[180px]"
>
{isLastQuestion ? 'Finish Quiz' : 'Next Question →'}
</Button>
</div>
</div>
)}
</div>
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
import { useState } from "react";
import { Card, Chip } from "@heroui/react";
interface Scenario {
name: string;
background: string;
solution: string;
code_example: string;
core_problem_solved: string;
key_considerations: string[];
}
interface ScenarioData {
scenarios: Scenario[];
}
interface Props {
topic: string;
data: ScenarioData | null;
loading: boolean;
error: string | null;
}
export default function Scenario({ topic, data, loading, error }: Props) {
const [expandedIndex, setExpandedIndex] = useState<number | null>(null);
const toggleScenario = (index: number) => {
setExpandedIndex(expandedIndex === index ? null : index);
};
if (loading) {
return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 p-8">
<div className="text-center text-gray-600">Loading...</div>
</Card>
</div>
);
}
if (error) {
return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 p-8">
<div className="text-center text-red-600">{error}</div>
</Card>
</div>
);
}
if (!topic || !data || data.scenarios.length === 0) {
return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 p-8">
<div className="absolute upper-0 right-0 -mr-2 -mb-2 pointer-events-none select-none">
<span className="text-[10rem] opacity-80 blur-none">💡</span>
</div>
<div className="text-center text-gray-600">
<div className="text-3xl mb-4">🌟</div>
<div className="text-lg font-medium mb-2">工程应用场景</div>
<div className="text-sm text-gray-500">输入主题后,这里将展示相关的工程应用场景和最佳实践</div>
</div>
</Card>
</div>
);
}
return (
<div className="w-full p-4 sm:p-6 md:max-w-2xl lg:max-w-4xl mx-auto">
<Card className="relative w-full max-w-2xl mx-auto bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100">
<div className="absolute upper-0 right-0 -mr-2 -mb-2 pointer-events-none select-none">
<span className="text-[10rem] opacity-80 blur-none">💡</span>
</div>
<div className="relative z-5">
<div className="px-6 pt-6 pb-4">
<Card.Title className="text-2xl font-bold text-gray-800 mb-2">
{topic} - 工程场景
</Card.Title>
<div className="h-1 w-20 bg-gradient-to-r from-purple-500 to-pink-500 rounded"></div>
<p className="mt-3 text-gray-600">
以下是该知识点的实际工程应用场景,帮助你理解如何在真实项目中使用
</p>
</div>
<div className="px-6 pb-6 space-y-3">
{data.scenarios.map((scenario, index) => {
const isExpanded = expandedIndex === index;
return (
<div
key={index}
className="border border-gray-200 rounded-xl overflow-hidden transition-all duration-200 hover:border-purple-300 hover:shadow-md"
>
<button
onClick={() => toggleScenario(index)}
className="w-full flex items-center gap-3 p-4 bg-white hover:bg-gray-50 transition-colors duration-200 cursor-pointer text-left"
>
<span className="text-2xl">🎯</span>
<span className="font-semibold text-gray-800 text-lg flex-1">
{scenario.name}
</span>
<Chip size="sm" variant="tertiary" color="accent">
场景 {index + 1}
</Chip>
<svg
className={`w-5 h-5 text-gray-500 transition-transform duration-200 flex-shrink-0 ${
isExpanded ? "rotate-180" : "rotate-0"
}`}
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
</button>
<div
className={`overflow-hidden transition-all duration-300 ease-in-out ${
isExpanded ? "max-h-[5000px] opacity-100" : "max-h-0 opacity-0"
}`}
>
<div className="p-4 pt-0 space-y-6">
<div>
<h4 className="flex items-center text-md font-semibold text-purple-700 mb-2">
<span className="mr-2">📋</span>
问题背景
</h4>
<p className="text-gray-700 pl-7 leading-relaxed">
{scenario.background}
</p>
</div>
<div>
<h4 className="flex items-center text-md font-semibold text-blue-700 mb-2">
<span className="mr-2">💡</span>
解决方案
</h4>
<p className="text-gray-700 pl-7 leading-relaxed">
{scenario.solution}
</p>
</div>
<div>
<h4 className="flex items-center text-md font-semibold text-green-700 mb-2">
<span className="mr-2">💻</span>
代码示例
</h4>
<div className="pl-7">
<pre className="bg-gray-900 text-green-400 p-4 rounded-lg overflow-x-auto text-sm font-mono leading-relaxed">
{scenario.code_example}
</pre>
</div>
</div>
<div>
<h4 className="flex items-center text-md font-semibold text-orange-700 mb-2">
<span className="mr-2">🎯</span>
核心问题解决
</h4>
<p className="text-gray-700 pl-7 leading-relaxed font-medium">
{scenario.core_problem_solved}
</p>
</div>
<div>
<h4 className="flex items-center text-md font-semibold text-red-700 mb-2">
<span className="mr-2">⚠️</span>
注意事项与最佳实践
</h4>
<ul className="space-y-2 pl-7">
{scenario.key_considerations.map((consideration, considerationIndex) => (
<li key={considerationIndex} className="flex items-start">
<span className="text-red-500 mr-2 mt-0.5 flex-shrink-0">
•
</span>
<span className="text-gray-700 leading-relaxed">
{consideration}
</span>
</li>
))}
</ul>
</div>
</div>
</div>
</div>
);
})}
</div>
</div>
</Card>
</div>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { Input, Button } from '@heroui/react';
import { useState } from 'react';
interface Props {
onTopicSubmit: (topic: string) => void;
}
export default function Default({ onTopicSubmit }: Props) {
const [value, setValue] = useState('');
const handleSubmit = () => {
if (value.trim()) {
onTopicSubmit(value);
}
};
const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
handleSubmit();
}
};
return (
<div className="flex gap-2 items-center">
<Input
aria-label="Name"
className="w-64"
placeholder="Please enter topic 🎉"
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyPress={handleKeyPress}
/>
<Button
variant="primary"
onPress={handleSubmit}
isDisabled={!value.trim()}
>
提交
</Button>
</div>
);
}