feat: update knowledge workspace and menu configuration
This commit is contained in:
1 parent
64a5305bbf
commit
8af4fed89d
28 files changed
+1250
-219
No files matched your search
@@ -0,0 +1,92 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { OptType, writeYLog } from "@/core/log/y-log";
|
||||
import type { CompactMenuOverride } from "@/core/page-layout/compact-menu-overrides";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/compact-menu-overrides`;
|
||||
|
||||
interface ServerCompactOverride {
|
||||
node_id: string;
|
||||
placement: "sidebar" | "settings";
|
||||
sort_order: number;
|
||||
label: string | null;
|
||||
}
|
||||
|
||||
function toOverride(s: ServerCompactOverride): CompactMenuOverride {
|
||||
return {
|
||||
nodeId: s.node_id,
|
||||
placement: s.placement === "settings" ? "settings" : "sidebar",
|
||||
sortOrder: s.sort_order ?? 0,
|
||||
label: s.label ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function toBody(o: CompactMenuOverride): ServerCompactOverride {
|
||||
return {
|
||||
node_id: o.nodeId,
|
||||
placement: o.placement,
|
||||
sort_order: o.sortOrder,
|
||||
label: o.label ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson<T>(res: Response, ctx: string): Promise<T> {
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null as unknown);
|
||||
const detail =
|
||||
data && typeof data === "object" && "detail" in data
|
||||
? String((data as { detail: unknown }).detail)
|
||||
: `${ctx} failed (${res.status})`;
|
||||
throw new Error(detail);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
export async function listCompactMenuOverrides(): Promise<CompactMenuOverride[]> {
|
||||
const res = await apiFetch(BASE(), { method: "GET" });
|
||||
const data = await readJson<{ overrides: ServerCompactOverride[] }>(res, "list compact menu overrides");
|
||||
return (data.overrides ?? []).map(toOverride);
|
||||
}
|
||||
|
||||
export async function replaceCompactMenuOverrides(
|
||||
overrides: CompactMenuOverride[],
|
||||
): Promise<CompactMenuOverride[]> {
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ overrides: overrides.map(toBody) }),
|
||||
});
|
||||
const data = await readJson<{ overrides: ServerCompactOverride[] }>(res, "save compact menu overrides");
|
||||
const saved = (data.overrides ?? []).map(toOverride);
|
||||
writeYLog({
|
||||
optType: OptType.edit,
|
||||
optDetail: "CM助手-简介-菜单管理-保存",
|
||||
url: "/api/compact-menu-overrides",
|
||||
reqParam: { overrides },
|
||||
returnParam: saved,
|
||||
});
|
||||
return saved;
|
||||
}
|
||||
|
||||
const COMPACT_MENU_OVERRIDES_KEY = "compact-menu-overrides";
|
||||
|
||||
export function useCompactMenuOverrides() {
|
||||
return useQuery({
|
||||
queryKey: [COMPACT_MENU_OVERRIDES_KEY],
|
||||
queryFn: listCompactMenuOverrides,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCompactMenuOverrideActions() {
|
||||
const queryClient = useQueryClient();
|
||||
return {
|
||||
save: useMutation({
|
||||
mutationFn: replaceCompactMenuOverrides,
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: [COMPACT_MENU_OVERRIDES_KEY] }),
|
||||
}),
|
||||
};
|
||||
}
|
||||
+5
-4
@@ -12,6 +12,7 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownCodeEditor } from "@/components/wiki/MarkdownCodeEditor";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import {
|
||||
createLlmWikiWeKnoraEmbedSession,
|
||||
@@ -435,7 +436,7 @@ function CurrentWikiArticleActions({
|
||||
删除
|
||||
</Button>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="flex max-h-[90vh] w-[calc(100vw-2rem)] max-w-4xl flex-col overflow-hidden">
|
||||
<DialogContent className="flex max-h-[94vh] w-[calc(100vw-2rem)] max-w-7xl flex-col overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle>编辑此文章</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -457,10 +458,10 @@ function CurrentWikiArticleActions({
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium">正文</label>
|
||||
<Textarea
|
||||
<MarkdownCodeEditor
|
||||
value={draft.content}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, content: event.target.value }))}
|
||||
className="min-h-[48vh] resize-y font-mono text-sm"
|
||||
onChange={(content) => setDraft((prev) => ({ ...prev, content }))}
|
||||
className="[&_.cm-editor]:min-h-[48vh]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -125,7 +125,7 @@ export function WeKnoraKnowledgeWorkspace() {
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="size-5 text-primary" />
|
||||
<h1 className="text-xl font-semibold">问答梳理</h1>
|
||||
<h1 className="text-xl font-semibold">知识库管理</h1>
|
||||
<Badge variant="secondary">知识服务</Badge>
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-muted-foreground">由知识服务负责解析与检索,用户、权限和发布范围由 cmzs 管理。</p>
|
||||
|
||||
+114
-20
@@ -1,5 +1,6 @@
|
||||
import { FileText, Loader2, Maximize2, Minimize2 } from "lucide-react";
|
||||
import { Download, FileText, Loader2, Maximize2, Minimize2 } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -13,7 +14,9 @@ import { apiFetch } from "@/core/api/fetch-client";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import type { WeKnoraSourceTarget } from "@/core/llmwiki/source-links";
|
||||
import { SpreadsheetPreview } from "@/components/workspace/artifacts/spreadsheet-preview";
|
||||
import { MarkdownContent } from "@/components/workspace/messages/markdown-content";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { reasoningPlugins } from "@/core/streamdown";
|
||||
import {
|
||||
getLlmWikiDocument,
|
||||
getLlmWikiDocumentPreview,
|
||||
@@ -44,10 +47,12 @@ type PreviewState =
|
||||
| { kind: "iframe"; url: string }
|
||||
| { kind: "xlsx"; data: ArrayBuffer }
|
||||
| { kind: "table"; rows: string[][]; highlightedRows: number[]; truncated: boolean; source: "csv" | "chunks" }
|
||||
| { kind: "markdown"; text: string }
|
||||
| { kind: "text"; text: string }
|
||||
| { kind: "unsupported"; message: string };
|
||||
|
||||
type CachedSourceDetail = {
|
||||
documentId: string;
|
||||
document: LlmWikiDocument | null;
|
||||
wikiPage: LlmWikiWikiPage | null;
|
||||
preview: PreviewState;
|
||||
@@ -104,6 +109,10 @@ function cleanText(value?: string | null) {
|
||||
return (value || "").replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
||||
}
|
||||
|
||||
function stripFrontmatter(value: string) {
|
||||
return value.replace(/^\s*---\s*\n[\s\S]*?\n---\s*(?:\n|$)/, "").trim();
|
||||
}
|
||||
|
||||
function fileExtension(document?: LlmWikiDocument | null) {
|
||||
const name = [document?.file_name, document?.title, document?.file_type]
|
||||
.filter(Boolean)
|
||||
@@ -165,6 +174,20 @@ function isTextPreview(blob: Blob, document?: LlmWikiDocument | null) {
|
||||
);
|
||||
}
|
||||
|
||||
function isMarkdownDocument(document?: LlmWikiDocument | null) {
|
||||
return ["md", "markdown"].includes(fileExtension(document));
|
||||
}
|
||||
|
||||
function isWordDocument(document?: LlmWikiDocument | null) {
|
||||
return ["doc", "docx"].includes(fileExtension(document));
|
||||
}
|
||||
|
||||
function markdownFromChunks(chunks: LlmWikiChunk[]) {
|
||||
return stripFrontmatter(
|
||||
chunks.map((chunk) => cleanText(chunk.content)).filter(Boolean).join("\n\n"),
|
||||
);
|
||||
}
|
||||
|
||||
function extractTerms(value: string, limit = 8) {
|
||||
return Array.from(
|
||||
new Set(
|
||||
@@ -240,6 +263,15 @@ async function buildPreviewState(
|
||||
const ext = fileExtension(document);
|
||||
const chunkTable = tableFromChunks(chunks, focusChunkId, quote);
|
||||
|
||||
// Browsers cannot render doc/docx blobs directly. WeKnora already parsed the
|
||||
// document into Markdown-like chunks, so use those for a faithful readable preview.
|
||||
if (isWordDocument(document)) {
|
||||
const text = markdownFromChunks(chunks);
|
||||
return text
|
||||
? { kind: "markdown", text }
|
||||
: { kind: "unsupported", message: "Word 文档已载入,但暂未取得可展示的解析正文。" };
|
||||
}
|
||||
|
||||
if (data.byteLength === 0 && chunkTable) {
|
||||
return chunkTable;
|
||||
}
|
||||
@@ -274,7 +306,9 @@ async function buildPreviewState(
|
||||
: text;
|
||||
return { kind: "table", ...parseCsv(delimiterNormalized), highlightedRows: [], source: "csv" };
|
||||
}
|
||||
return { kind: "text", text };
|
||||
return isMarkdownDocument(document)
|
||||
? { kind: "markdown", text }
|
||||
: { kind: "text", text };
|
||||
}
|
||||
|
||||
return { kind: "iframe", url: URL.createObjectURL(blob) };
|
||||
@@ -367,13 +401,13 @@ function DataTablePreview({
|
||||
<table className="w-max min-w-full border-separate border-spacing-0 overflow-hidden rounded-lg border bg-background text-sm shadow-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="sticky left-0 top-0 z-20 w-12 border-b border-r bg-slate-100 px-2 py-2.5 text-center text-xs font-medium text-muted-foreground">
|
||||
<th className="w-12 border-b border-r bg-slate-100 px-2 py-2.5 text-center text-xs font-medium text-muted-foreground dark:bg-slate-800">
|
||||
#
|
||||
</th>
|
||||
{Array.from({ length: columnCount }, (_, columnIndex) => (
|
||||
<th
|
||||
key={columnIndex}
|
||||
className="sticky top-0 z-10 border-b border-r bg-slate-100 px-3 py-2.5 text-left font-semibold text-foreground whitespace-nowrap"
|
||||
className="border-b border-r bg-slate-100 px-3 py-2.5 text-left font-semibold text-foreground whitespace-nowrap dark:bg-slate-800"
|
||||
>
|
||||
{headerRow?.[columnIndex] ?? ""}
|
||||
</th>
|
||||
@@ -433,6 +467,8 @@ export function WeKnoraSourceDrawer({
|
||||
const [previewError, setPreviewError] = useState("");
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
const [fullscreen, setFullscreen] = useState(false);
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const [resolvedDocumentId, setResolvedDocumentId] = useState("");
|
||||
|
||||
const targetKey = useMemo(() => {
|
||||
if (!target) return "";
|
||||
@@ -455,6 +491,7 @@ export function WeKnoraSourceDrawer({
|
||||
setPreviewLoading(false);
|
||||
setPreview({ kind: "none" });
|
||||
setFullscreen(false);
|
||||
setResolvedDocumentId("");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -462,6 +499,7 @@ export function WeKnoraSourceDrawer({
|
||||
const cached = sourceDetailCache.get(targetKey);
|
||||
if (cached) {
|
||||
setDocument(cached.document);
|
||||
setResolvedDocumentId(cached.documentId);
|
||||
setWikiPage(cached.wikiPage);
|
||||
setPreview(cached.preview);
|
||||
setPreviewError(cached.previewError);
|
||||
@@ -480,6 +518,7 @@ export function WeKnoraSourceDrawer({
|
||||
|
||||
void (async () => {
|
||||
const detailTarget = await resolveTargetDetail(target);
|
||||
if (!cancelled) setResolvedDocumentId(detailTarget.documentId || "");
|
||||
const tasks: Promise<void>[] = [];
|
||||
let loadedDocument: LlmWikiDocument | null = null;
|
||||
let loadedWikiPage: LlmWikiWikiPage | null = null;
|
||||
@@ -516,7 +555,10 @@ export function WeKnoraSourceDrawer({
|
||||
setLoading(false);
|
||||
setPreviewLoading(true);
|
||||
}
|
||||
const previewTask = getLlmWikiDocumentPreview(detailTarget.knowledgeBaseId, detailTarget.documentId)
|
||||
const previewBlobPromise = isWordDocument(loadedDocument)
|
||||
? Promise.resolve(new Blob())
|
||||
: getLlmWikiDocumentPreview(detailTarget.knowledgeBaseId, detailTarget.documentId);
|
||||
const previewTask = previewBlobPromise
|
||||
.then((blob) => {
|
||||
return buildPreviewState(
|
||||
blob,
|
||||
@@ -547,6 +589,7 @@ export function WeKnoraSourceDrawer({
|
||||
}
|
||||
await Promise.all(tasks);
|
||||
sourceDetailCache.set(targetKey, {
|
||||
documentId: detailTarget.documentId || "",
|
||||
document: loadedDocument,
|
||||
wikiPage: loadedWikiPage,
|
||||
preview: loadedPreview,
|
||||
@@ -574,7 +617,27 @@ export function WeKnoraSourceDrawer({
|
||||
title ||
|
||||
"文档详情";
|
||||
const summary = cleanText(wikiPage?.summary || document?.description);
|
||||
const wikiContent = cleanText(wikiPage?.content);
|
||||
const wikiContent = stripFrontmatter(cleanText(wikiPage?.content));
|
||||
|
||||
const downloadOriginal = async () => {
|
||||
if (!target || !resolvedDocumentId) return;
|
||||
setDownloading(true);
|
||||
try {
|
||||
const blob = await getLlmWikiDocumentPreview(target.knowledgeBaseId, resolvedDocumentId);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = window.document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = document?.file_name || document?.title || resolvedTitle || "document";
|
||||
window.document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "下载原文失败");
|
||||
} finally {
|
||||
setDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
@@ -588,7 +651,7 @@ export function WeKnoraSourceDrawer({
|
||||
<SheetTitle className="sr-only">{resolvedTitle}</SheetTitle>
|
||||
<SheetDescription className="sr-only">知识库文档详情</SheetDescription>
|
||||
<div className="relative flex h-full min-h-0 flex-col bg-background">
|
||||
<div className="shrink-0 border-b px-5 py-4 pr-24">
|
||||
<div className="shrink-0 border-b px-5 py-4 pr-64">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-emerald-100 text-emerald-700">
|
||||
<FileText className="size-5" />
|
||||
@@ -604,17 +667,24 @@ export function WeKnoraSourceDrawer({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="absolute top-4 right-12"
|
||||
onClick={() => setFullscreen((value) => !value)}
|
||||
aria-label={fullscreen ? "退出全屏" : "全屏打开参考文献源文件"}
|
||||
title={fullscreen ? "退出全屏" : "全屏打开参考文献源文件"}
|
||||
>
|
||||
{fullscreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
|
||||
</Button>
|
||||
<div className="absolute top-4 right-12 flex items-center gap-2">
|
||||
{resolvedDocumentId && (
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => void downloadOriginal()} disabled={downloading}>
|
||||
{downloading ? <Loader2 className="size-4 animate-spin" /> : <Download className="size-4" />}
|
||||
下载原文
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setFullscreen((value) => !value)}
|
||||
aria-label={fullscreen ? "退出放大查看" : "单独放大查看文档"}
|
||||
>
|
||||
{fullscreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
|
||||
{fullscreen ? "退出放大" : "放大查看"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
@@ -672,6 +742,24 @@ export function WeKnoraSourceDrawer({
|
||||
</section>
|
||||
)}
|
||||
|
||||
{preview.kind === "markdown" && (
|
||||
<section className="border-b bg-slate-100/70 px-4 py-6 dark:bg-slate-950/50 sm:px-8">
|
||||
<article className="mx-auto max-w-4xl rounded-xl border bg-background px-6 py-7 shadow-sm sm:px-10">
|
||||
<div className="mb-6 flex items-center gap-2 border-b pb-4 text-sm font-medium text-muted-foreground">
|
||||
<FileText className="size-4" />
|
||||
{isWordDocument(document) ? "Word 文档预览" : "Markdown 文档预览"}
|
||||
</div>
|
||||
<MarkdownContent
|
||||
className="max-w-none"
|
||||
content={preview.text}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
/>
|
||||
</article>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{preview.kind === "unsupported" && (
|
||||
<section className="border-b px-5 py-4 text-sm text-muted-foreground">
|
||||
{preview.message}
|
||||
@@ -695,8 +783,14 @@ export function WeKnoraSourceDrawer({
|
||||
{wikiContent && (
|
||||
<section className="border-b px-5 py-4">
|
||||
<div className="mb-2 text-sm font-medium text-foreground">Wiki 原文</div>
|
||||
<div className="prose prose-sm max-w-none whitespace-pre-wrap text-foreground">
|
||||
{wikiContent}
|
||||
<div className="rounded-lg border bg-background p-5">
|
||||
<MarkdownContent
|
||||
className="max-w-none"
|
||||
content={wikiContent}
|
||||
isLoading={false}
|
||||
remarkPlugins={reasoningPlugins.remarkPlugins}
|
||||
rehypePlugins={reasoningPlugins.rehypePlugins}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
+3
-3
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownCodeEditor } from "@/components/wiki/MarkdownCodeEditor";
|
||||
import {
|
||||
type LlmWikiWikiPage,
|
||||
useLlmWikiActions,
|
||||
@@ -747,10 +748,9 @@ export function WeKnoraWikiManagementPage() {
|
||||
</label>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-sm font-medium">正文</span>
|
||||
<Textarea
|
||||
<MarkdownCodeEditor
|
||||
value={draft.content}
|
||||
onChange={(event) => setDraft((prev) => ({ ...prev, content: event.target.value }))}
|
||||
className="min-h-[46vh] resize-y font-mono text-sm"
|
||||
onChange={(content) => setDraft((prev) => ({ ...prev, content }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user