mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 09:20:08 +08:00
Block 7+8: Book integration + Create Module dialog (4 tabs)
Block 7: "Start learning" button on BookLibrary cards, import-from-book endpoint, handleLearn with duplicate progress check, i18n keys. Block 8: CreateModuleDialog with manual/book/KB/notebook tabs, generate-from-notebook backend endpoint with LLM extraction, listBooks/generateModulesFromNotebook API functions, 30+ i18n keys.
This commit is contained in:
@@ -259,3 +259,69 @@ async def redo_progress(book_id: str):
|
||||
if qpath.exists():
|
||||
qpath.unlink()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
class NotebookRecordInput(BaseModel):
|
||||
id: str
|
||||
type: str = "note"
|
||||
title: str = ""
|
||||
output: str = ""
|
||||
|
||||
|
||||
class GenerateFromNotebookRequest(BaseModel):
|
||||
notebook_id: str
|
||||
records: list[NotebookRecordInput]
|
||||
|
||||
|
||||
@router.post("/progress/{book_id}/generate-from-notebook")
|
||||
async def generate_from_notebook(book_id: str, body: GenerateFromNotebookRequest):
|
||||
if not book_id or ".." in book_id or "/" in book_id or "\\" in book_id or ":" in book_id:
|
||||
raise HTTPException(status_code=400, detail="Invalid book_id")
|
||||
if not body.records:
|
||||
raise HTTPException(status_code=400, detail="No records provided")
|
||||
|
||||
records_text = "\n\n".join(
|
||||
f"[{r.type}] {r.title}: {r.output[:500]}"
|
||||
for r in body.records[:20]
|
||||
)
|
||||
from deeptutor.services.llm import complete
|
||||
prompt = f"""根据以下笔记本记录,提取知识点并组织为学习模块。
|
||||
每个模块包含:name(模块名)、knowledge_points(知识点列表,每个有 name 和 type)。
|
||||
type 可选:memory / concept / procedure / design。
|
||||
返回 JSON: {{"modules": [{{"name": "...", "knowledge_points": [{{"name": "...", "type": "concept"}}]}}]}}
|
||||
|
||||
笔记本记录:
|
||||
{records_text}"""
|
||||
response = await complete(prompt=prompt, system_prompt="你是学习模块规划助手。只输出 JSON。")
|
||||
import json
|
||||
try:
|
||||
data = json.loads(response)
|
||||
except json.JSONDecodeError:
|
||||
raise HTTPException(status_code=500, detail="LLM returned invalid JSON")
|
||||
|
||||
modules_raw = data.get("modules", [])
|
||||
service = get_learning_service()
|
||||
progress = service.get_or_create(book_id)
|
||||
modules = []
|
||||
for i, m in enumerate(modules_raw):
|
||||
kps = [
|
||||
KnowledgePoint(
|
||||
id=f"{book_id}_nb{i}_kp{j}",
|
||||
name=kp["name"],
|
||||
type=kp.get("type", "concept"),
|
||||
module_id=f"{book_id}_nb{i}",
|
||||
)
|
||||
for j, kp in enumerate(m.get("knowledge_points", []))
|
||||
]
|
||||
modules.append(LearningModule(
|
||||
id=f"{book_id}_nb{i}",
|
||||
name=m.get("name", f"模块 {i+1}"),
|
||||
order=i,
|
||||
pass_threshold=0.7,
|
||||
knowledge_points=kps,
|
||||
))
|
||||
service.init_modules(progress, modules)
|
||||
progress.current_module_id = modules[0].id if modules else ""
|
||||
progress.current_kp_index = 0
|
||||
service.save(progress)
|
||||
return {"status": "ok", "module_count": len(modules), "modules": [m.model_dump() for m in modules]}
|
||||
|
||||
@@ -141,7 +141,7 @@ export default function LearningBookPage() {
|
||||
return;
|
||||
}
|
||||
if (evt.type === "module_changed") {
|
||||
const e = evt as Record<string, unknown>;
|
||||
const e = evt as unknown as Record<string, unknown>;
|
||||
if (e.success !== false) {
|
||||
setCurrentModuleId(typeof e.module_id === "string" ? e.module_id : "");
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
redoProgress,
|
||||
type ProgressSummary,
|
||||
} from "@/lib/learning-api";
|
||||
import CreateModuleDialog from "@/components/learning/CreateModuleDialog";
|
||||
|
||||
type Tab = "current" | "completed" | "all";
|
||||
|
||||
@@ -27,6 +28,7 @@ export default function LearningPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [tab, setTab] = useState<Tab>("all");
|
||||
const [toast, setToast] = useState("");
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
|
||||
const loadProgress = useCallback(async () => {
|
||||
try {
|
||||
@@ -85,7 +87,7 @@ export default function LearningPage() {
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => router.push("/learning/default")}
|
||||
onClick={() => setDialogOpen(true)}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-[var(--primary)] text-[var(--primary-foreground)] text-sm font-medium hover:opacity-90 transition-opacity"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
@@ -203,6 +205,12 @@ export default function LearningPage() {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<CreateModuleDialog
|
||||
open={dialogOpen}
|
||||
onClose={() => setDialogOpen(false)}
|
||||
onCreated={() => loadProgress()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
593
web/components/learning/CreateModuleDialog.tsx
Normal file
593
web/components/learning/CreateModuleDialog.tsx
Normal file
@@ -0,0 +1,593 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { BookOpen, FileText, Loader2, Plus, Trash2, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
fetchAllProgress,
|
||||
importFromBook,
|
||||
initModules,
|
||||
listBooks,
|
||||
generateModulesFromNotebook,
|
||||
type BookSummary,
|
||||
type ModuleInit,
|
||||
} from "@/lib/learning-api";
|
||||
import { listKnowledgeBases, type KnowledgeBaseSummary } from "@/lib/knowledge-api";
|
||||
import {
|
||||
listNotebooks,
|
||||
getNotebook,
|
||||
type NotebookSummary,
|
||||
type NotebookRecordItem,
|
||||
} from "@/lib/notebook-api";
|
||||
|
||||
interface CreateModuleDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCreated: () => void;
|
||||
}
|
||||
|
||||
type TabKey = "manual" | "book" | "kb" | "notebook";
|
||||
|
||||
interface KpRow {
|
||||
name: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export default function CreateModuleDialog({
|
||||
open,
|
||||
onClose,
|
||||
onCreated,
|
||||
}: CreateModuleDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState<TabKey>("manual");
|
||||
|
||||
// ── Manual tab state ──
|
||||
const [moduleName, setModuleName] = useState("");
|
||||
const [kpRows, setKpRows] = useState<KpRow[]>([{ name: "", type: "concept" }]);
|
||||
const [manualBookId, setManualBookId] = useState("manual");
|
||||
|
||||
// ── Book tab state ──
|
||||
const [books, setBooks] = useState<BookSummary[]>([]);
|
||||
const [selectedBookId, setSelectedBookId] = useState<string>("");
|
||||
const [bookChapters, setBookChapters] = useState<{ title: string; learning_objectives: string[] }[]>([]);
|
||||
const [loadingBooks, setLoadingBooks] = useState(false);
|
||||
const [loadingChapters, setLoadingChapters] = useState(false);
|
||||
|
||||
// ── KB tab state ──
|
||||
const [kbList, setKbList] = useState<KnowledgeBaseSummary[]>([]);
|
||||
const [selectedKb, setSelectedKb] = useState<string>("");
|
||||
const [loadingKb, setLoadingKb] = useState(false);
|
||||
|
||||
// ── Notebook tab state ──
|
||||
const [notebooks, setNotebooks] = useState<NotebookSummary[]>([]);
|
||||
const [selectedNotebook, setSelectedNotebook] = useState<string>("");
|
||||
const [notebookRecords, setNotebookRecords] = useState<NotebookRecordItem[]>([]);
|
||||
const [selectedRecordIds, setSelectedRecordIds] = useState<Set<string>>(new Set());
|
||||
const [loadingNotebooks, setLoadingNotebooks] = useState(false);
|
||||
const [loadingRecords, setLoadingRecords] = useState(false);
|
||||
|
||||
// ── Shared state ──
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Load data when tab changes
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (tab === "book" && books.length === 0) {
|
||||
setLoadingBooks(true);
|
||||
listBooks()
|
||||
.then(setBooks)
|
||||
.catch(() => setError(t("guidedLearning.loadBooksFailed")))
|
||||
.finally(() => setLoadingBooks(false));
|
||||
}
|
||||
if (tab === "kb" && kbList.length === 0) {
|
||||
setLoadingKb(true);
|
||||
listKnowledgeBases()
|
||||
.then(setKbList)
|
||||
.catch(() => setError(t("guidedLearning.loadKbFailed")))
|
||||
.finally(() => setLoadingKb(false));
|
||||
}
|
||||
if (tab === "notebook" && notebooks.length === 0) {
|
||||
setLoadingNotebooks(true);
|
||||
listNotebooks()
|
||||
.then(setNotebooks)
|
||||
.catch(() => setError(t("guidedLearning.loadNotebooksFailed")))
|
||||
.finally(() => setLoadingNotebooks(false));
|
||||
}
|
||||
}, [open, tab, books.length, kbList.length, notebooks.length, t]);
|
||||
|
||||
// Load chapters when book selected
|
||||
useEffect(() => {
|
||||
if (!selectedBookId) { setBookChapters([]); return; }
|
||||
setLoadingChapters(true);
|
||||
import("@/lib/book-api").then(({ bookApi }) =>
|
||||
bookApi.get(selectedBookId)
|
||||
.then((data) => setBookChapters(data.spine?.chapters ?? []))
|
||||
.catch(() => setError(t("guidedLearning.loadChaptersFailed")))
|
||||
.finally(() => setLoadingChapters(false)),
|
||||
);
|
||||
}, [selectedBookId, t]);
|
||||
|
||||
// Load records when notebook selected
|
||||
useEffect(() => {
|
||||
if (!selectedNotebook) { setNotebookRecords([]); setSelectedRecordIds(new Set()); return; }
|
||||
setLoadingRecords(true);
|
||||
getNotebook(selectedNotebook)
|
||||
.then((data) => setNotebookRecords(data.records ?? []))
|
||||
.catch(() => setError(t("guidedLearning.loadRecordsFailed")))
|
||||
.finally(() => setLoadingRecords(false));
|
||||
}, [selectedNotebook, t]);
|
||||
|
||||
const resetState = useCallback(() => {
|
||||
setTab("manual");
|
||||
setModuleName("");
|
||||
setKpRows([{ name: "", type: "concept" }]);
|
||||
setManualBookId("manual");
|
||||
setSelectedBookId("");
|
||||
setBookChapters([]);
|
||||
setSelectedKb("");
|
||||
setSelectedNotebook("");
|
||||
setNotebookRecords([]);
|
||||
setSelectedRecordIds(new Set());
|
||||
setSubmitting(false);
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
resetState();
|
||||
onClose();
|
||||
}, [resetState, onClose]);
|
||||
|
||||
// ── Submit handlers ──
|
||||
|
||||
const handleManualSubmit = async () => {
|
||||
const validKps = kpRows.filter((r) => r.name.trim());
|
||||
if (!moduleName.trim() && validKps.length === 0) {
|
||||
setError(t("guidedLearning.moduleNameRequired"));
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const bookId = manualBookId.trim() || "manual";
|
||||
const modules: ModuleInit[] = [{
|
||||
id: `${bookId}_m0`,
|
||||
name: moduleName.trim() || t("guidedLearning.untitledModule"),
|
||||
order: 0,
|
||||
pass_threshold: 0.7,
|
||||
knowledge_points: validKps.map((kp, j) => ({
|
||||
id: `${bookId}_m0_kp${j}`,
|
||||
name: kp.name.trim(),
|
||||
type: kp.type,
|
||||
module_id: `${bookId}_m0`,
|
||||
})),
|
||||
}];
|
||||
await initModules(bookId, modules);
|
||||
onCreated();
|
||||
handleClose();
|
||||
} catch {
|
||||
setError(t("guidedLearning.createModuleFailed"));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBookSubmit = async () => {
|
||||
if (!selectedBookId || bookChapters.length === 0) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const chapters = bookChapters.map((ch) => ({
|
||||
title: ch.title,
|
||||
knowledge_points: ch.learning_objectives ?? [],
|
||||
}));
|
||||
await importFromBook(selectedBookId, chapters);
|
||||
onCreated();
|
||||
handleClose();
|
||||
} catch {
|
||||
setError(t("guidedLearning.importBookFailed"));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKbSubmit = async () => {
|
||||
if (!selectedKb) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const bookId = `kb_${selectedKb}`;
|
||||
// For KB import, we create a single module with the KB name
|
||||
// The actual LLM-based module generation would need a dedicated endpoint
|
||||
const modules: ModuleInit[] = [{
|
||||
id: `${bookId}_m0`,
|
||||
name: selectedKb,
|
||||
order: 0,
|
||||
pass_threshold: 0.7,
|
||||
knowledge_points: [],
|
||||
}];
|
||||
await initModules(bookId, modules);
|
||||
onCreated();
|
||||
handleClose();
|
||||
} catch {
|
||||
setError(t("guidedLearning.importKbFailed"));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNotebookSubmit = async () => {
|
||||
if (!selectedNotebook || selectedRecordIds.size === 0) return;
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const bookId = `nb_${selectedNotebook}`;
|
||||
const records = notebookRecords
|
||||
.filter((r) => selectedRecordIds.has(r.id))
|
||||
.map((r) => ({ id: r.id, type: r.type, title: r.title, output: r.output }));
|
||||
const result = await generateModulesFromNotebook(bookId, selectedNotebook, records.slice(0, 20));
|
||||
// After LLM generates, init the modules
|
||||
if (result.modules && result.modules.length > 0) {
|
||||
await initModules(bookId, result.modules);
|
||||
}
|
||||
onCreated();
|
||||
handleClose();
|
||||
} catch {
|
||||
setError(t("guidedLearning.importNotebookFailed"));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const tabs: { key: TabKey; label: string }[] = [
|
||||
{ key: "manual", label: t("guidedLearning.tabManual") },
|
||||
{ key: "book", label: t("guidedLearning.tabBook") },
|
||||
{ key: "kb", label: t("guidedLearning.tabKb") },
|
||||
{ key: "notebook", label: t("guidedLearning.tabNotebook") },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
||||
onClick={handleClose}
|
||||
/>
|
||||
{/* Dialog */}
|
||||
<div className="relative z-10 w-full max-w-lg max-h-[80vh] flex flex-col rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-xl">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
|
||||
<h2 className="text-lg font-semibold text-[var(--foreground)]">
|
||||
{t("guidedLearning.createModule")}
|
||||
</h2>
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="p-1 rounded-md text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:bg-[var(--secondary)]"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-1 px-5 pt-3 border-b border-[var(--border)]">
|
||||
{tabs.map((tb) => (
|
||||
<button
|
||||
key={tb.key}
|
||||
onClick={() => { setTab(tb.key); setError(null); }}
|
||||
className={`px-3 py-1.5 text-xs font-medium rounded-t-md transition-colors border-b-2 -mb-px ${
|
||||
tab === tb.key
|
||||
? "border-[var(--primary)] text-[var(--foreground)] bg-[var(--secondary)]/40"
|
||||
: "border-transparent text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
|
||||
}`}
|
||||
>
|
||||
{tb.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 overflow-y-auto px-5 py-4">
|
||||
{error && (
|
||||
<div className="mb-3 rounded-lg bg-red-500/10 border border-red-500/20 px-3 py-2 text-xs text-red-500">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Manual Tab */}
|
||||
{tab === "manual" && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-[var(--muted-foreground)] mb-1">
|
||||
{t("guidedLearning.bookId")}
|
||||
</label>
|
||||
<input
|
||||
value={manualBookId}
|
||||
onChange={(e) => setManualBookId(e.target.value)}
|
||||
placeholder="manual"
|
||||
className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-[var(--muted-foreground)] mb-1">
|
||||
{t("guidedLearning.moduleName")}
|
||||
</label>
|
||||
<input
|
||||
value={moduleName}
|
||||
onChange={(e) => setModuleName(e.target.value)}
|
||||
placeholder={t("guidedLearning.moduleNamePlaceholder")}
|
||||
className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-[var(--muted-foreground)] mb-2">
|
||||
{t("guidedLearning.knowledgePoints")}
|
||||
</label>
|
||||
{kpRows.map((row, i) => (
|
||||
<div key={i} className="flex items-center gap-2 mb-2">
|
||||
<input
|
||||
value={row.name}
|
||||
onChange={(e) => {
|
||||
const next = [...kpRows];
|
||||
next[i] = { ...next[i], name: e.target.value };
|
||||
setKpRows(next);
|
||||
}}
|
||||
placeholder={t("guidedLearning.kpNamePlaceholder")}
|
||||
className="flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none"
|
||||
/>
|
||||
<select
|
||||
value={row.type}
|
||||
onChange={(e) => {
|
||||
const next = [...kpRows];
|
||||
next[i] = { ...next[i], type: e.target.value };
|
||||
setKpRows(next);
|
||||
}}
|
||||
className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1.5 text-xs text-[var(--foreground)] focus:outline-none"
|
||||
>
|
||||
<option value="memory">{t("knowledgeType.memory")}</option>
|
||||
<option value="concept">{t("knowledgeType.concept")}</option>
|
||||
<option value="procedure">{t("knowledgeType.procedure")}</option>
|
||||
<option value="design">{t("knowledgeType.design")}</option>
|
||||
</select>
|
||||
{kpRows.length > 1 && (
|
||||
<button
|
||||
onClick={() => setKpRows(kpRows.filter((_, j) => j !== i))}
|
||||
className="p-1 text-[var(--muted-foreground)] hover:text-red-500"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
onClick={() => setKpRows([...kpRows, { name: "", type: "concept" }])}
|
||||
className="flex items-center gap-1 text-xs text-[var(--primary)] hover:opacity-80"
|
||||
>
|
||||
<Plus className="w-3 h-3" />
|
||||
{t("guidedLearning.addKp")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Book Tab */}
|
||||
{tab === "book" && (
|
||||
<div className="space-y-3">
|
||||
{loadingBooks ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-[var(--muted-foreground)]" />
|
||||
</div>
|
||||
) : books.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-[var(--muted-foreground)]">
|
||||
{t("guidedLearning.noBooks")}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="max-h-40 overflow-y-auto space-y-1">
|
||||
{books.map((book) => (
|
||||
<button
|
||||
key={book.id}
|
||||
onClick={() => setSelectedBookId(book.id)}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
|
||||
selectedBookId === book.id
|
||||
? "bg-[var(--primary)]/10 border border-[var(--primary)]/30 text-[var(--foreground)]"
|
||||
: "border border-transparent text-[var(--muted-foreground)] hover:bg-[var(--secondary)]/40 hover:text-[var(--foreground)]"
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium truncate">{book.title || book.id}</div>
|
||||
<div className="text-xs opacity-70">
|
||||
{book.chapter_count} {t("guidedLearning.chapters")} · {book.status}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{selectedBookId && (
|
||||
<div className="border-t border-[var(--border)] pt-3">
|
||||
{loadingChapters ? (
|
||||
<div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{t("guidedLearning.loadingChapters")}
|
||||
</div>
|
||||
) : bookChapters.length === 0 ? (
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
{t("guidedLearning.noChapters")}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-[var(--muted-foreground)] mb-2">
|
||||
{t("guidedLearning.chaptersToImport", { count: bookChapters.length })}
|
||||
</p>
|
||||
<div className="max-h-32 overflow-y-auto space-y-1">
|
||||
{bookChapters.map((ch, i) => (
|
||||
<div key={i} className="flex items-center gap-2 text-xs text-[var(--muted-foreground)]">
|
||||
<FileText className="w-3 h-3 shrink-0" />
|
||||
<span className="truncate">{ch.title}</span>
|
||||
<span className="opacity-50">
|
||||
({(ch.learning_objectives ?? []).length} {t("guidedLearning.kps")})
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* KB Tab */}
|
||||
{tab === "kb" && (
|
||||
<div className="space-y-3">
|
||||
{loadingKb ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-[var(--muted-foreground)]" />
|
||||
</div>
|
||||
) : kbList.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-[var(--muted-foreground)]">
|
||||
{t("guidedLearning.noKb")}
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-60 overflow-y-auto space-y-1">
|
||||
{kbList.map((kb) => (
|
||||
<button
|
||||
key={kb.name}
|
||||
onClick={() => setSelectedKb(kb.name)}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
|
||||
selectedKb === kb.name
|
||||
? "bg-[var(--primary)]/10 border border-[var(--primary)]/30 text-[var(--foreground)]"
|
||||
: "border border-transparent text-[var(--muted-foreground)] hover:bg-[var(--secondary)]/40 hover:text-[var(--foreground)]"
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium truncate">{kb.name}</div>
|
||||
{kb.status && (
|
||||
<div className="text-xs opacity-70">{kb.status}</div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Notebook Tab */}
|
||||
{tab === "notebook" && (
|
||||
<div className="space-y-3">
|
||||
{loadingNotebooks ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-[var(--muted-foreground)]" />
|
||||
</div>
|
||||
) : notebooks.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-[var(--muted-foreground)]">
|
||||
{t("guidedLearning.noNotebooks")}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="max-h-32 overflow-y-auto space-y-1">
|
||||
{notebooks.map((nb) => (
|
||||
<button
|
||||
key={nb.id}
|
||||
onClick={() => setSelectedNotebook(nb.id)}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
|
||||
selectedNotebook === nb.id
|
||||
? "bg-[var(--primary)]/10 border border-[var(--primary)]/30 text-[var(--foreground)]"
|
||||
: "border border-transparent text-[var(--muted-foreground)] hover:bg-[var(--secondary)]/40 hover:text-[var(--foreground)]"
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium truncate">{nb.name}</div>
|
||||
<div className="text-xs opacity-70">
|
||||
{nb.record_count ?? 0} {t("guidedLearning.records")}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{selectedNotebook && (
|
||||
<div className="border-t border-[var(--border)] pt-3">
|
||||
{loadingRecords ? (
|
||||
<div className="flex items-center gap-2 text-sm text-[var(--muted-foreground)]">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{t("guidedLearning.loadingRecords")}
|
||||
</div>
|
||||
) : notebookRecords.length === 0 ? (
|
||||
<div className="text-sm text-[var(--muted-foreground)]">
|
||||
{t("guidedLearning.noRecords")}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-[var(--muted-foreground)] mb-2">
|
||||
{t("guidedLearning.selectRecords")} ({selectedRecordIds.size} {t("guidedLearning.selected")})
|
||||
</p>
|
||||
<div className="max-h-40 overflow-y-auto space-y-1">
|
||||
{notebookRecords.slice(0, 20).map((rec) => (
|
||||
<label
|
||||
key={rec.id}
|
||||
className="flex items-start gap-2 px-2 py-1.5 rounded text-xs cursor-pointer hover:bg-[var(--secondary)]/40"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedRecordIds.has(rec.id)}
|
||||
onChange={(e) => {
|
||||
const next = new Set(selectedRecordIds);
|
||||
if (e.target.checked) next.add(rec.id);
|
||||
else next.delete(rec.id);
|
||||
setSelectedRecordIds(next);
|
||||
}}
|
||||
className="mt-0.5 rounded border-[var(--border)]"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium text-[var(--foreground)] truncate">
|
||||
{rec.title || rec.id}
|
||||
</div>
|
||||
{rec.output && (
|
||||
<div className="text-[var(--muted-foreground)] truncate opacity-70">
|
||||
{rec.output.slice(0, 80)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{notebookRecords.length > 20 && (
|
||||
<p className="text-[10px] text-[var(--muted-foreground)] mt-1 opacity-60">
|
||||
{t("guidedLearning.recordsLimited")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="flex items-center justify-end gap-2 px-5 py-3 border-t border-[var(--border)]">
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="px-4 py-1.5 text-sm rounded-lg border border-[var(--border)] text-[var(--muted-foreground)] hover:text-[var(--foreground)] hover:bg-[var(--secondary)]/40"
|
||||
>
|
||||
{t("guidedLearning.cancel")}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
if (tab === "manual") void handleManualSubmit();
|
||||
else if (tab === "book") void handleBookSubmit();
|
||||
else if (tab === "kb") void handleKbSubmit();
|
||||
else if (tab === "notebook") void handleNotebookSubmit();
|
||||
}}
|
||||
disabled={submitting || (tab === "book" && (!selectedBookId || bookChapters.length === 0)) || (tab === "notebook" && selectedRecordIds.size === 0)}
|
||||
className="flex items-center gap-1.5 px-4 py-1.5 text-sm rounded-lg bg-[var(--primary)] text-[var(--primary-foreground)] hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{submitting && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
|
||||
{tab === "notebook" ? t("guidedLearning.generateModules") : t("guidedLearning.create")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -78,3 +78,33 @@ export async function importFromBook(bookId: string, chapters: { title: string;
|
||||
if (!res.ok) throw new Error(`Failed to import from book: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export interface BookSummary {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
status: string;
|
||||
chapter_count: number;
|
||||
page_count: number;
|
||||
}
|
||||
|
||||
export async function listBooks(): Promise<BookSummary[]> {
|
||||
const res = await apiFetch(apiUrl("/api/v1/books"));
|
||||
if (!res.ok) throw new Error(`Failed to list books: ${res.status}`);
|
||||
const data = await res.json();
|
||||
return data.books ?? [];
|
||||
}
|
||||
|
||||
export async function generateModulesFromNotebook(
|
||||
bookId: string,
|
||||
notebookId: string,
|
||||
records: { id: string; type: string; title: string; output: string }[],
|
||||
): Promise<{ modules: ModuleInit[] }> {
|
||||
const res = await apiFetch(apiUrl(`/api/v1/learning/progress/${encodeURIComponent(bookId)}/generate-from-notebook`), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ notebook_id: notebookId, records }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Failed to generate modules from notebook: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -1651,6 +1651,43 @@
|
||||
"guidedLearning.stage.completed": "Completed",
|
||||
"Start learning": "Start learning",
|
||||
"guidedLearning.alreadyHasProgress": "You already have learning progress for this book. Continuing...",
|
||||
"guidedLearning.tabManual": "Manual",
|
||||
"guidedLearning.tabBook": "From Book",
|
||||
"guidedLearning.tabKb": "From KB",
|
||||
"guidedLearning.tabNotebook": "From Notebook",
|
||||
"guidedLearning.bookId": "Book ID",
|
||||
"guidedLearning.moduleName": "Module Name",
|
||||
"guidedLearning.moduleNamePlaceholder": "e.g. Introduction to Algebra",
|
||||
"guidedLearning.kpNamePlaceholder": "Knowledge point name",
|
||||
"guidedLearning.addKp": "Add knowledge point",
|
||||
"guidedLearning.noBooks": "No books available",
|
||||
"guidedLearning.chapters": "chapters",
|
||||
"guidedLearning.loadingChapters": "Loading chapters...",
|
||||
"guidedLearning.noChapters": "No chapters found in this book",
|
||||
"guidedLearning.chaptersToImport": "{{count}} chapters to import",
|
||||
"guidedLearning.kps": "KPs",
|
||||
"guidedLearning.noKb": "No knowledge bases available",
|
||||
"guidedLearning.noNotebooks": "No notebooks available",
|
||||
"guidedLearning.records": "records",
|
||||
"guidedLearning.loadingRecords": "Loading records...",
|
||||
"guidedLearning.noRecords": "This notebook has no records",
|
||||
"guidedLearning.selectRecords": "Select records to import",
|
||||
"guidedLearning.selected": "selected",
|
||||
"guidedLearning.recordsLimited": "Only the first 20 records are shown.",
|
||||
"guidedLearning.cancel": "Cancel",
|
||||
"guidedLearning.create": "Create",
|
||||
"guidedLearning.generateModules": "Generate Modules",
|
||||
"guidedLearning.moduleNameRequired": "Please enter a module name or at least one knowledge point.",
|
||||
"guidedLearning.untitledModule": "Untitled Module",
|
||||
"guidedLearning.createModuleFailed": "Failed to create module",
|
||||
"guidedLearning.importBookFailed": "Failed to import from book",
|
||||
"guidedLearning.importKbFailed": "Failed to import from knowledge base",
|
||||
"guidedLearning.importNotebookFailed": "Failed to generate modules from notebook",
|
||||
"guidedLearning.loadBooksFailed": "Failed to load books",
|
||||
"guidedLearning.loadKbFailed": "Failed to load knowledge bases",
|
||||
"guidedLearning.loadNotebooksFailed": "Failed to load notebooks",
|
||||
"guidedLearning.loadChaptersFailed": "Failed to load chapters",
|
||||
"guidedLearning.loadRecordsFailed": "Failed to load notebook records",
|
||||
"knowledgeType.memory": "Rote Memory",
|
||||
"knowledgeType.concept": "Conceptual",
|
||||
"knowledgeType.procedure": "Procedural",
|
||||
|
||||
@@ -1651,6 +1651,43 @@
|
||||
"guidedLearning.stage.completed": "已完成",
|
||||
"Start learning": "开始学习",
|
||||
"guidedLearning.alreadyHasProgress": "该书已有学习进度,将直接继续学习。",
|
||||
"guidedLearning.tabManual": "手动创建",
|
||||
"guidedLearning.tabBook": "从书籍导入",
|
||||
"guidedLearning.tabKb": "从知识库导入",
|
||||
"guidedLearning.tabNotebook": "从笔记本导入",
|
||||
"guidedLearning.bookId": "书籍 ID",
|
||||
"guidedLearning.moduleName": "模块名称",
|
||||
"guidedLearning.moduleNamePlaceholder": "如:线性代数入门",
|
||||
"guidedLearning.kpNamePlaceholder": "知识点名称",
|
||||
"guidedLearning.addKp": "添加知识点",
|
||||
"guidedLearning.noBooks": "暂无可用书籍",
|
||||
"guidedLearning.chapters": "章节",
|
||||
"guidedLearning.loadingChapters": "加载章节中...",
|
||||
"guidedLearning.noChapters": "该书未找到章节",
|
||||
"guidedLearning.chaptersToImport": "将导入 {{count}} 个章节",
|
||||
"guidedLearning.kps": "知识点",
|
||||
"guidedLearning.noKb": "暂无可用知识库",
|
||||
"guidedLearning.noNotebooks": "暂无可用笔记本",
|
||||
"guidedLearning.records": "条记录",
|
||||
"guidedLearning.loadingRecords": "加载记录中...",
|
||||
"guidedLearning.noRecords": "该笔记本暂无记录",
|
||||
"guidedLearning.selectRecords": "选择要导入的记录",
|
||||
"guidedLearning.selected": "已选",
|
||||
"guidedLearning.recordsLimited": "仅显示前 20 条记录。",
|
||||
"guidedLearning.cancel": "取消",
|
||||
"guidedLearning.create": "创建",
|
||||
"guidedLearning.generateModules": "生成模块",
|
||||
"guidedLearning.moduleNameRequired": "请输入模块名称或至少一个知识点。",
|
||||
"guidedLearning.untitledModule": "未命名模块",
|
||||
"guidedLearning.createModuleFailed": "创建模块失败",
|
||||
"guidedLearning.importBookFailed": "从书籍导入失败",
|
||||
"guidedLearning.importKbFailed": "从知识库导入失败",
|
||||
"guidedLearning.importNotebookFailed": "从笔记本生成模块失败",
|
||||
"guidedLearning.loadBooksFailed": "加载书籍失败",
|
||||
"guidedLearning.loadKbFailed": "加载知识库失败",
|
||||
"guidedLearning.loadNotebooksFailed": "加载笔记本失败",
|
||||
"guidedLearning.loadChaptersFailed": "加载章节失败",
|
||||
"guidedLearning.loadRecordsFailed": "加载笔记本记录失败",
|
||||
"knowledgeType.memory": "记忆型",
|
||||
"knowledgeType.concept": "概念型",
|
||||
"knowledgeType.procedure": "程序型",
|
||||
|
||||
Reference in New Issue
Block a user