添加推荐问题修改接口

This commit is contained in:
fengxiangdebaozi committed 2026-05-14 11:07:28 +08:00
1 parent 62292500ba
commit 2f2ba44c7c
13 files changed
+481 -126

No files matched your search

@@ -82,6 +82,7 @@ import {
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
import { useThread } from "./messages/context";
import { ModeHoverGuide } from "./mode-hover-guide";
import { Tooltip } from "./tooltip";
@@ -164,7 +165,7 @@ export function InputBox({
null,
);
const [recommendedQuestions] = useRecommendedQuestions();
const { questions: recommendedQuestions } = useRecommendedQuestions();
useEffect(() => {
if (models.length === 0) {
@@ -0,0 +1,66 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import type {
CreateQuestionRequest,
RecommendedQuestion,
UpdateQuestionRequest,
} from "./index";
const BASE = () => `${getBackendBaseURL()}/api/recommended-questions`;
export async function listRecommendedQuestions(): Promise<RecommendedQuestion[]> {
const res = await apiFetch(BASE());
if (!res.ok) throw new Error(`Failed to load questions: ${res.statusText}`);
const data = (await res.json()) as { questions: RecommendedQuestion[] };
return data.questions;
}
export async function createRecommendedQuestion(
body: CreateQuestionRequest,
): Promise<RecommendedQuestion> {
const res = await apiFetch(BASE(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to create question: ${res.statusText}`);
}
return res.json() as Promise<RecommendedQuestion>;
}
export async function updateRecommendedQuestion(
id: string,
body: UpdateQuestionRequest,
): Promise<RecommendedQuestion> {
const res = await apiFetch(`${BASE()}/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to update question: ${res.statusText}`);
}
return res.json() as Promise<RecommendedQuestion>;
}
export async function deleteRecommendedQuestion(id: string): Promise<void> {
const res = await apiFetch(`${BASE()}/${id}`, { method: "DELETE" });
if (!res.ok) throw new Error(`Failed to delete question: ${res.statusText}`);
}
export async function reorderRecommendedQuestions(
ids: string[],
): Promise<RecommendedQuestion[]> {
const res = await apiFetch(`${getBackendBaseURL()}/api/recommended-questions-reorder`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids }),
});
if (!res.ok) throw new Error(`Failed to reorder questions: ${res.statusText}`);
const data = (await res.json()) as { questions: RecommendedQuestion[] };
return data.questions;
}
@@ -1,58 +1,53 @@
import { useCallback, useSyncExternalStore } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
DEFAULT_QUESTIONS,
getRecommendedQuestions,
saveRecommendedQuestions,
type RecommendedQuestion,
} from "./index";
createRecommendedQuestion,
deleteRecommendedQuestion,
listRecommendedQuestions,
reorderRecommendedQuestions,
updateRecommendedQuestion,
} from "./api";
import type { CreateQuestionRequest, UpdateQuestionRequest } from "./index";
type Listener = () => void;
const QK = ["recommended-questions"] as const;
const listeners = new Set<Listener>();
let cached: RecommendedQuestion[] | null = null;
function getSnapshot(): RecommendedQuestion[] {
if (cached === null) {
cached = getRecommendedQuestions();
}
return cached;
export function useRecommendedQuestions() {
const { data, isLoading, error } = useQuery({
queryKey: QK,
queryFn: listRecommendedQuestions,
});
return { questions: data ?? [], isLoading, error };
}
function getServerSnapshot(): RecommendedQuestion[] {
return DEFAULT_QUESTIONS;
export function useCreateRecommendedQuestion() {
const qc = useQueryClient();
return useMutation({
mutationFn: (body: CreateQuestionRequest) => createRecommendedQuestion(body),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
function subscribe(listener: Listener): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
export function useUpdateRecommendedQuestion() {
const qc = useQueryClient();
return useMutation({
mutationFn: ({ id, body }: { id: string; body: UpdateQuestionRequest }) =>
updateRecommendedQuestion(id, body),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
function emitChange() {
for (const l of listeners) l();
export function useDeleteRecommendedQuestion() {
const qc = useQueryClient();
return useMutation({
mutationFn: (id: string) => deleteRecommendedQuestion(id),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
export function updateRecommendedQuestions(
questions: RecommendedQuestion[],
): void {
cached = questions;
saveRecommendedQuestions(questions);
emitChange();
}
export function useRecommendedQuestions(): [
RecommendedQuestion[],
(questions: RecommendedQuestion[]) => void,
] {
const questions = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
const save = useCallback((qs: RecommendedQuestion[]) => {
updateRecommendedQuestions(qs);
}, []);
return [questions, save];
export function useReorderRecommendedQuestions() {
const qc = useQueryClient();
return useMutation({
mutationFn: (ids: string[]) => reorderRecommendedQuestions(ids),
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
});
}
@@ -2,56 +2,19 @@ export interface RecommendedQuestion {
id: string;
title: string;
content: string;
sort_order: number;
created_at?: string;
updated_at?: string;
}
const STORAGE_KEY = "deerflow.recommended-questions";
export const DEFAULT_QUESTIONS: RecommendedQuestion[] = [
{
id: "default-1",
title: "市场分析报告",
content:
"请帮我写一份关于当前 AI 市场的详细分析报告,包括市场规模、主要玩家和发展趋势。",
},
{
id: "default-2",
title: "制定学习计划",
content:
"请帮我制定一个为期 3 个月的 Python 编程学习计划,从基础到进阶,每周安排具体任务。",
},
{
id: "default-3",
title: "代码审查建议",
content:
"请帮我审查代码,找出潜在的问题、性能瓶颈以及改进建议,并给出修改示例。",
},
{
id: "default-4",
title: "数据分析方案",
content:
"请帮我设计一个用于分析用户行为数据的方案,包括数据收集、处理和可视化策略。",
},
{
id: "default-5",
title: "文章润色优化",
content: "请帮我润色以下文章,使其更加流畅、专业,并保持原意不变。",
},
];
export function getRecommendedQuestions(): RecommendedQuestion[] {
if (typeof window === "undefined") return DEFAULT_QUESTIONS;
const json = localStorage.getItem(STORAGE_KEY);
if (!json) return DEFAULT_QUESTIONS;
try {
const parsed = JSON.parse(json) as RecommendedQuestion[];
if (Array.isArray(parsed) && parsed.length > 0) return parsed;
} catch {}
return DEFAULT_QUESTIONS;
export interface CreateQuestionRequest {
title: string;
content: string;
sort_order?: number;
}
export function saveRecommendedQuestions(
questions: RecommendedQuestion[],
): void {
if (typeof window === "undefined") return;
localStorage.setItem(STORAGE_KEY, JSON.stringify(questions));
export interface UpdateQuestionRequest {
title?: string;
content?: string;
sort_order?: number;
}
@@ -1,7 +1,13 @@
"use client";
import { useState } from "react";
import { GripVerticalIcon, PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";
import {
GripVerticalIcon,
Loader2Icon,
PencilIcon,
PlusIcon,
Trash2Icon,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
@@ -14,7 +20,13 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
import {
useCreateRecommendedQuestion,
useDeleteRecommendedQuestion,
useRecommendedQuestions,
useReorderRecommendedQuestions,
useUpdateRecommendedQuestion,
} from "@/core/recommended-questions/hooks";
import type { RecommendedQuestion } from "@/core/recommended-questions";
type DialogState =
@@ -22,12 +34,13 @@ type DialogState =
| { mode: "edit"; question: RecommendedQuestion }
| null;
function generateId() {
return `q-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
}
export default function RecommendedQuestionsPage() {
const [questions, setQuestions] = useRecommendedQuestions();
const { questions, isLoading, error } = useRecommendedQuestions();
const createMutation = useCreateRecommendedQuestion();
const updateMutation = useUpdateRecommendedQuestion();
const deleteMutation = useDeleteRecommendedQuestion();
const reorderMutation = useReorderRecommendedQuestions();
const [dialog, setDialog] = useState<DialogState>(null);
const [formTitle, setFormTitle] = useState("");
const [formContent, setFormContent] = useState("");
@@ -53,7 +66,7 @@ export default function RecommendedQuestionsPage() {
setDialog(null);
}
function handleSave() {
async function handleSave() {
const title = formTitle.trim();
const content = formContent.trim();
if (!title || !content) {
@@ -61,24 +74,35 @@ export default function RecommendedQuestionsPage() {
return;
}
if (dialog?.mode === "add") {
setQuestions([...questions, { id: generateId(), title, content }]);
toast.success("问题已添加");
} else if (dialog?.mode === "edit") {
setQuestions(
questions.map((q) =>
q.id === dialog.question.id ? { ...q, title, content } : q,
),
);
toast.success("问题已更新");
try {
if (dialog?.mode === "add") {
await createMutation.mutateAsync({
title,
content,
sort_order: questions.length,
});
toast.success("问题已添加");
} else if (dialog?.mode === "edit") {
await updateMutation.mutateAsync({
id: dialog.question.id,
body: { title, content },
});
toast.success("问题已更新");
}
closeDialog();
} catch (e) {
toast.error(e instanceof Error ? e.message : "操作失败");
}
closeDialog();
}
function handleDelete(q: RecommendedQuestion) {
setQuestions(questions.filter((item) => item.id !== q.id));
setDeleteTarget(null);
toast.success("问题已删除");
async function handleDelete(q: RecommendedQuestion) {
try {
await deleteMutation.mutateAsync(q.id);
setDeleteTarget(null);
toast.success("问题已删除");
} catch (e) {
toast.error(e instanceof Error ? e.message : "删除失败");
}
}
function handleDragStart(index: number) {
@@ -90,7 +114,7 @@ export default function RecommendedQuestionsPage() {
setDragOverIndex(index);
}
function handleDrop(toIndex: number) {
async function handleDrop(toIndex: number) {
if (dragIndex === null || dragIndex === toIndex) {
setDragIndex(null);
setDragOverIndex(null);
@@ -99,11 +123,21 @@ export default function RecommendedQuestionsPage() {
const next = [...questions];
const [moved] = next.splice(dragIndex, 1);
next.splice(toIndex, 0, moved!);
setQuestions(next);
setDragIndex(null);
setDragOverIndex(null);
try {
await reorderMutation.mutateAsync(next.map((q) => q.id));
} catch {
toast.error("排序保存失败");
}
}
const isSaving =
createMutation.isPending ||
updateMutation.isPending ||
deleteMutation.isPending ||
reorderMutation.isPending;
return (
<div className="mx-auto flex w-full max-w-2xl flex-col gap-6 px-6 py-10">
<div className="flex items-center justify-between">
@@ -113,13 +147,21 @@ export default function RecommendedQuestionsPage() {
管理首页展示的推荐问题,点击后直接发送到对话。拖拽可调整顺序。
</p>
</div>
<Button onClick={openAdd} className="shrink-0">
<Button onClick={openAdd} className="shrink-0" disabled={isLoading}>
<PlusIcon className="mr-1.5 size-4" />
添加问题
</Button>
</div>
{questions.length === 0 ? (
{isLoading ? (
<div className="flex items-center justify-center py-16">
<Loader2Icon className="text-muted-foreground size-6 animate-spin" />
</div>
) : error ? (
<div className="text-destructive flex flex-col items-center gap-2 rounded-xl border border-dashed py-16 text-sm">
<p>加载失败:{error.message}</p>
</div>
) : questions.length === 0 ? (
<div className="text-muted-foreground flex flex-col items-center gap-3 rounded-xl border border-dashed py-16 text-sm">
<p>暂无推荐问题</p>
<Button variant="outline" size="sm" onClick={openAdd}>
@@ -161,6 +203,7 @@ export default function RecommendedQuestionsPage() {
size="icon"
className="size-7"
onClick={() => openEdit(q)}
disabled={isSaving}
>
<PencilIcon className="size-3.5" />
</Button>
@@ -169,6 +212,7 @@ export default function RecommendedQuestionsPage() {
size="icon"
className="text-destructive hover:text-destructive size-7"
onClick={() => setDeleteTarget(q)}
disabled={isSaving}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -206,10 +250,11 @@ export default function RecommendedQuestionsPage() {
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={closeDialog}>
<Button variant="outline" onClick={closeDialog} disabled={isSaving}>
取消
</Button>
<Button onClick={handleSave}>
<Button onClick={handleSave} disabled={isSaving}>
{isSaving && <Loader2Icon className="mr-1.5 size-4 animate-spin" />}
{dialog?.mode === "add" ? "添加" : "保存"}
</Button>
</DialogFooter>
@@ -229,13 +274,21 @@ export default function RecommendedQuestionsPage() {
确定要删除「{deleteTarget?.title}」吗?此操作不可撤销。
</p>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteTarget(null)}>
<Button
variant="outline"
onClick={() => setDeleteTarget(null)}
disabled={isSaving}
>
取消
</Button>
<Button
variant="destructive"
disabled={isSaving}
onClick={() => deleteTarget && handleDelete(deleteTarget)}
>
{deleteMutation.isPending && (
<Loader2Icon className="mr-1.5 size-4 animate-spin" />
)}
删除
</Button>
</DialogFooter>