Files
mnote/wolai-frontend/src/components/editor/blocks/MindmapSidebar.tsx
T

680 lines
23 KiB
TypeScript
Raw Normal View History

/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useMemo, useState } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Toggle } from "@/components/ui/toggle";
import {
Bold,
Italic,
Underline,
Type,
Strikethrough,
Palette,
X,
Network,
ListTree,
Sliders,
Calculator,
StickyNote,
Bot,
} from "lucide-react";
import {
fontFamilyList,
fontSizeList,
lineHeightList,
colorList,
borderDasharrayList,
borderRadiusList,
borderWidthList,
lineWidthList,
shapeList,
lineStyleList,
themeList,
layoutList,
outlineDepthOptions,
} from "./mindmapOptions";
type MindMapNode = {
getStyle: (prop: string, checkRoot?: boolean) => any;
setStyle: (prop: string, value: any) => void;
setIcon: (icons: string[]) => void;
getData: (key: string) => any;
};
type SidebarProps = {
mindmap: any;
activeNodes: MindMapNode[];
activeTab: SidebarPanel | null;
onClose: () => void;
};
const predefinedIcons = [
{
type: 'priority',
name: '优先级',
list: ['1', '2', '3', '4', '5', '6', '7', '8', '9']
},
{
type: 'progress',
name: '进度',
list: ['start', 'quarter', 'half', '3quarter', 'done'] // Standard keys usually
}
];
const ColorInput = ({
value,
onChange,
label,
}: {
value: string;
onChange: (val: string) => void;
label?: string;
}) => (
<div className="flex items-center gap-2">
{label && <span className="text-xs text-gray-500">{label}</span>}
<div className="relative h-6 w-full flex-1 overflow-hidden rounded border border-gray-200">
<input
type="color"
value={value || "#000000"}
onChange={(e) => onChange(e.target.value)}
className="absolute inset-[-50%] h-[200%] w-[200%] cursor-pointer border-0 p-0"
/>
</div>
</div>
);
const NativeSelect = ({
value,
onChange,
options,
placeholder,
disabled,
}: {
value: string | number;
onChange: (val: string) => void;
options: { label: string | number; value: string | number }[];
placeholder?: string;
disabled?: boolean;
}) => (
<div className="relative">
<select
disabled={disabled}
value={value}
onChange={(e) => onChange(e.target.value)}
className="flex h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 appearance-none"
>
{placeholder && <option value="" disabled>{placeholder}</option>}
{options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
);
const StylePanel = ({ activeNodes }: { activeNodes: MindMapNode[] }) => {
const [style, setStyle] = useState<Record<string, any>>({});
useEffect(() => {
if (activeNodes.length > 0) {
const node = activeNodes[0];
const newStyle: Record<string, any> = {};
[
"fontFamily", "fontSize", "lineHeight", "color", "fontWeight", "fontStyle",
"textDecoration", "borderWidth", "borderColor", "fillColor", "shape",
"lineColor", "lineWidth", "lineDasharray", "borderRadius", "borderDasharray"
].forEach((prop) => {
newStyle[prop] = node.getStyle(prop, false);
});
// eslint-disable-next-line react-hooks/set-state-in-effect
setStyle(newStyle);
}
}, [activeNodes]);
const updateStyle = (prop: string, value: any) => {
setStyle((prev) => ({ ...prev, [prop]: value }));
activeNodes.forEach((node) => {
node.setStyle(prop, value);
});
};
if (activeNodes.length === 0) {
return (
<div className="flex h-full flex-col items-center justify-center p-4 text-center text-gray-400">
<Type className="mb-2 h-10 w-10 opacity-20" />
<p className="text-sm">请选择一个节点以编辑样式</p>
</div>
);
}
return (
<div className="space-y-6">
<div className="space-y-3">
<Label className="text-xs font-semibold text-gray-500">文字</Label>
<NativeSelect
value={style.fontFamily || fontFamilyList[0]?.value}
options={fontFamilyList.map((f) => ({ label: f.name, value: f.value }))}
onChange={(v) => updateStyle("fontFamily", v)}
/>
<div className="grid grid-cols-2 gap-2">
<NativeSelect
value={style.fontSize || 14}
options={fontSizeList.map((s) => ({ label: `${s}px`, value: s }))}
onChange={(v) => updateStyle("fontSize", Number(v))}
/>
<NativeSelect
value={style.lineHeight || 1.5}
options={lineHeightList.map((h) => ({ label: h, value: h }))}
onChange={(v) => updateStyle("lineHeight", Number(v))}
/>
</div>
<div className="flex items-center gap-2">
<Toggle
size="sm"
pressed={style.fontWeight === "bold"}
onPressedChange={(pressed) => updateStyle("fontWeight", pressed ? "bold" : "normal")}
>
<Bold className="h-4 w-4" />
</Toggle>
<Toggle
size="sm"
pressed={style.fontStyle === "italic"}
onPressedChange={(pressed) => updateStyle("fontStyle", pressed ? "italic" : "normal")}
>
<Italic className="h-4 w-4" />
</Toggle>
<Toggle
size="sm"
pressed={style.textDecoration === "underline"}
onPressedChange={(pressed) => updateStyle("textDecoration", pressed ? "underline" : "none")}
>
<Underline className="h-4 w-4" />
</Toggle>
<Toggle
size="sm"
pressed={style.textDecoration === "line-through"}
onPressedChange={(pressed) => updateStyle("textDecoration", pressed ? "line-through" : "none")}
>
<Strikethrough className="h-4 w-4" />
</Toggle>
</div>
<ColorInput
label="颜色"
value={style.color}
onChange={(v) => updateStyle("color", v)}
/>
</div>
<div className="space-y-3">
<Label className="text-xs font-semibold text-gray-500">边框 & 背景</Label>
<div className="grid grid-cols-2 gap-2">
<NativeSelect
value={style.shape || "rectangle"}
options={shapeList.map(s => ({label: s.name, value: s.value}))}
onChange={(v) => updateStyle("shape", v)}
/>
<NativeSelect
value={style.borderDasharray || "none"}
options={borderDasharrayList.map(s => ({label: s.name, value: s.value}))}
onChange={(v) => updateStyle("borderDasharray", v)}
/>
</div>
<div className="grid grid-cols-2 gap-2">
<NativeSelect
value={Number.isFinite(style.borderWidth) ? style.borderWidth : (style.borderWidth ?? 0)}
options={borderWidthList.map((n) => ({ label: `${n}px`, value: n }))}
onChange={(v) => updateStyle("borderWidth", Number(v))}
/>
<NativeSelect
value={Number.isFinite(style.borderRadius) ? style.borderRadius : (style.borderRadius ?? 0)}
options={borderRadiusList.map((n) => ({ label: `${n}px`, value: n }))}
onChange={(v) => updateStyle("borderRadius", Number(v))}
/>
</div>
<div className="grid grid-cols-2 gap-2">
<ColorInput
label="边框"
value={style.borderColor}
onChange={(v) => updateStyle("borderColor", v)}
/>
<ColorInput
label="填充"
value={style.fillColor}
onChange={(v) => updateStyle("fillColor", v)}
/>
</div>
</div>
<div className="space-y-3">
<Label className="text-xs font-semibold text-gray-500">连线</Label>
<div className="grid grid-cols-2 gap-2">
<NativeSelect
value={style.lineDasharray || "none"}
options={borderDasharrayList.map(s => ({label: s.name, value: s.value}))}
onChange={(v) => updateStyle("lineDasharray", v)}
/>
<NativeSelect
value={Number.isFinite(style.lineWidth) ? style.lineWidth : (style.lineWidth ?? 0)}
options={lineWidthList.map((n) => ({ label: `${n}px`, value: n }))}
onChange={(v) => updateStyle("lineWidth", Number(v))}
/>
</div>
<ColorInput
label="连线颜色"
value={style.lineColor}
onChange={(v) => updateStyle("lineColor", v)}
/>
</div>
</div>
);
};
const BaseStylePanel = ({ mindmap }: { mindmap: any }) => {
const [style, setStyle] = useState<Record<string, any>>({});
useEffect(() => {
if (!mindmap) return;
const initStyle = () => {
const newStyle: Record<string, any> = {};
[
"backgroundColor", "lineColor", "lineWidth", "lineStyle",
"paddingX", "paddingY"
].forEach(key => {
newStyle[key] = mindmap.getThemeConfig(key);
});
setStyle(newStyle);
};
initStyle();
}, [mindmap]);
const updateThemeConfig = (key: string, value: any) => {
if (!mindmap) return;
setStyle(prev => ({ ...prev, [key]: value }));
mindmap.setThemeConfig({ [key]: value });
};
if (!mindmap) return null;
return (
<div className="space-y-6">
<div className="space-y-3">
<Label className="text-xs font-semibold text-gray-500">背景</Label>
<ColorInput
label="背景颜色"
value={style.backgroundColor}
onChange={(v) => updateThemeConfig("backgroundColor", v)}
/>
</div>
<div className="space-y-3">
<Label className="text-xs font-semibold text-gray-500">连线 (默认)</Label>
<div className="grid grid-cols-2 gap-2">
<NativeSelect
value={style.lineStyle || "curve"}
options={lineStyleList.map(s => ({ label: s.name, value: s.value }))}
onChange={(v) => updateThemeConfig("lineStyle", v)}
/>
<NativeSelect
value={Number.isFinite(style.lineWidth) ? style.lineWidth : (style.lineWidth ?? 0)}
options={lineWidthList.map((n) => ({ label: `${n}px`, value: n }))}
onChange={(v) => updateThemeConfig("lineWidth", Number(v))}
/>
</div>
<ColorInput
label="连线颜色"
value={style.lineColor}
onChange={(v) => updateThemeConfig("lineColor", v)}
/>
</div>
<div className="space-y-3">
<Label className="text-xs font-semibold text-gray-500">节点内边距 (默认)</Label>
<div className="grid grid-cols-2 gap-2">
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 whitespace-nowrap">水平</span>
<Input
type="number"
className="h-8"
min={0}
value={parseInt(style.paddingX) || 0}
onChange={e => updateThemeConfig("paddingX", Number(e.target.value))}
/>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500 whitespace-nowrap">垂直</span>
<Input
type="number"
className="h-8"
min={0}
value={parseInt(style.paddingY) || 0}
onChange={e => updateThemeConfig("paddingY", Number(e.target.value))}
/>
</div>
</div>
</div>
</div>
);
};
const ThemePanel = ({ mindmap }: { mindmap: any }) => {
const changeTheme = (theme: string) => {
if (!mindmap) return;
mindmap.setTheme(theme);
};
if (!mindmap) return null;
return (
<div className="grid grid-cols-2 gap-3">
{themeList.map(t => (
<button
key={t.value}
onClick={() => changeTheme(t.value)}
className="flex flex-col items-center justify-center rounded border border-gray-100 bg-gray-50 p-3 hover:border-blue-500 hover:bg-blue-50"
>
<Palette className="mb-2 h-6 w-6 text-gray-400" />
<span className="text-xs text-gray-600">{t.name}</span>
</button>
))}
</div>
)
}
const StructurePanel = ({ mindmap }: { mindmap: any }) => {
const changeLayout = (layout: string) => {
if (!mindmap) return;
mindmap.setLayout(layout);
};
if (!mindmap) return null;
return (
<div className="grid grid-cols-2 gap-3">
{layoutList.map(l => (
<button
key={l.value}
onClick={() => changeLayout(l.value)}
className="flex flex-col items-center justify-center rounded border border-gray-100 bg-gray-50 p-3 hover:border-blue-500 hover:bg-blue-50"
>
<Network className="mb-2 h-6 w-6 text-gray-400" />
<span className="text-xs text-gray-600">{l.name}</span>
</button>
))}
</div>
)
}
const IconPanel = ({ activeNodes }: { activeNodes: MindMapNode[] }) => {
const addIcon = (type: string, name: string) => {
// simple-mind-map icon key format usually: type_name (e.g. priority_1)
const key = `${type}_${name}`;
activeNodes.forEach(node => {
const icons = node.getData('icon') || [];
// Remove existing icon of same type
const newIcons = icons.filter((i: string) => !i.startsWith(type + '_'));
newIcons.push(key);
node.setIcon(newIcons);
});
};
const removeIcon = (type: string) => {
activeNodes.forEach(node => {
const icons = node.getData('icon') || [];
const newIcons = icons.filter((i: string) => !i.startsWith(type + '_'));
node.setIcon(newIcons);
});
}
if (activeNodes.length === 0) return <div className="p-4 text-center text-gray-400">请选择节点</div>;
return (
<div className="space-y-4 py-2">
{predefinedIcons.map(group => (
<div key={group.type}>
<div className="mb-2 flex items-center justify-between">
<Label className="text-xs font-bold text-gray-600">{group.name}</Label>
<button onClick={() => removeIcon(group.type)} className="text-[10px] text-red-500 hover:underline">清除</button>
</div>
<div className="flex flex-wrap gap-2">
{group.list.map(item => (
<button
key={item}
onClick={() => addIcon(group.type, item)}
className="flex h-8 w-8 items-center justify-center rounded border border-gray-200 bg-gray-50 text-xs hover:bg-blue-50 hover:border-blue-300"
>
{item}
</button>
))}
</div>
</div>
))}
<div className="text-xs text-gray-400 mt-4">
* 更多图标需接入 SVG 资源库
</div>
</div>
);
}
const OutlinePanel = ({ mindmap }: { mindmap: any }) => {
const [depth, setDepth] = useState<number>(-1);
const nodes = useMemo(() => {
const root = mindmap?.renderer?.renderTree?._node;
const list: { node: any; text: string; depth: number }[] = [];
const walk = (n: any, d: number) => {
if (!n) return;
const raw =
n.nodeData?.data?.text ||
n.nodeData?.text ||
n.data?.text ||
n.data?.data?.text ||
"未命名";
const text =
typeof raw === "string"
? raw.replace(/<[^>]+>/g, "").trim() || "未命名"
: "未命名";
list.push({ node: n, text, depth: d });
(n.children || []).forEach((c: any) => walk(c, d + 1));
};
if (root) walk(root, 0);
return list;
}, [mindmap]);
const visibleNodes = useMemo(
() => nodes.filter((item) => depth < 0 || item.depth < depth),
[nodes, depth],
);
const activate = (node: any) => {
const r = mindmap?.renderer;
if (!node || !r) return;
r.activeNodeList = [node];
r.lastActiveNodeList = [node];
mindmap.emit?.("node_active", node, [node]);
r.setRootNodeCenter?.();
};
if (!nodes.length) return <div className="p-4 text-sm text-gray-400">暂无节点</div>;
return (
<div className="space-y-3">
<div>
<Label className="text-xs text-gray-500">显示层级</Label>
<NativeSelect
value={depth}
options={outlineDepthOptions.map((o) => ({ label: o.name, value: o.value }))}
onChange={(v) => setDepth(Number(v))}
/>
</div>
<div className="max-h-[70vh] space-y-1 overflow-auto pr-2">
{visibleNodes.map((item, idx) => (
<button
key={`${item.text}-${idx}`}
className="flex w-full items-center gap-2 rounded-lg px-2 py-1 text-left text-sm hover:bg-gray-50"
onClick={() => activate(item.node)}
>
<span className="text-gray-300" style={{ paddingLeft: item.depth * 12 }}>
{"•".repeat(Math.max(1, item.depth + 1))}
</span>
<span className="text-gray-700">{item.text}</span>
</button>
))}
</div>
</div>
);
};
const SettingsPanel = ({ mindmap }: { mindmap: any }) => {
const [freeDrag, setFreeDrag] = useState<boolean>(!!mindmap?.opt?.enableFreeDrag);
const [wheel, setWheel] = useState<string>(mindmap?.opt?.mousewheelAction || "zoom");
const [aiOn, setAiOn] = useState<boolean>(true);
const updateFreeDrag = (val: boolean) => {
setFreeDrag(val);
if (mindmap) mindmap.opt.enableFreeDrag = val;
};
const updateWheel = (val: string) => {
setWheel(val);
if (mindmap) mindmap.opt.mousewheelAction = val;
};
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<Label className="text-xs text-gray-500">自由拖拽</Label>
<Toggle size="sm" pressed={freeDrag} onPressedChange={updateFreeDrag}>
{freeDrag ? "开" : "关"}
</Toggle>
</div>
<div className="space-y-2">
<Label className="text-xs text-gray-500">滚轮行为</Label>
<NativeSelect
value={wheel}
onChange={updateWheel}
options={[
{ label: "缩放", value: "zoom" },
{ label: "平移", value: "move" },
]}
/>
</div>
<div className="flex items-center justify-between">
<Label className="text-xs text-gray-500">AI 功能</Label>
<Toggle size="sm" pressed={aiOn} onPressedChange={setAiOn}>
{aiOn ? "开" : "关"}
</Toggle>
</div>
<p className="text-xs text-gray-400">其余设置后续接入(滚轮缩放方向、拖拽导入等)。</p>
</div>
);
};
const FormulaPanel = ({ mindmap }: { mindmap: any }) => {
const [formula, setFormula] = useState("a^2+b^2=c^2");
const insert = () => {
const active = mindmap?.renderer?.activeNodeList || [];
mindmap?.execCommand?.("INSERT_FORMULA", formula, active);
};
return (
<div className="space-y-3">
<Label className="text-xs text-gray-500">LaTeX 公式</Label>
<Input value={formula} onChange={(e) => setFormula(e.target.value)} />
<button className="w-full rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600" onClick={insert}>
插入公式
</button>
</div>
);
};
const NotePanel = ({ mindmap }: { mindmap: any }) => {
const [note, setNote] = useState("备注内容");
const apply = () => {
const active = mindmap?.renderer?.activeNodeList || [];
active.forEach((node: any) => mindmap?.execCommand?.("SET_NODE_NOTE", node, note));
};
return (
<div className="space-y-3">
<Label className="text-xs text-gray-500">节点备注</Label>
<Input value={note} onChange={(e) => setNote(e.target.value)} />
<button className="w-full rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600" onClick={apply}>
应用到选中节点
</button>
</div>
);
};
const AiPanel = () => {
const [prompt, setPrompt] = useState("");
const send = () => window.alert("AI 对话占位,后续接入大模型:\n" + prompt);
return (
<div className="space-y-3">
<Label className="text-xs text-gray-500">AI 对话</Label>
<textarea
className="w-full rounded-md border border-gray-200 p-2 text-sm"
rows={4}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="输入需求,后续将调用 AI 生成/优化节点"
/>
<button className="w-full rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600" onClick={send}>
发送
</button>
</div>
);
};
import { sidebarTitles, type SidebarPanel } from "./mindmapSidebarConfig";
export const MindmapSidebar = ({ mindmap, activeNodes, activeTab, onClose }: SidebarProps) => {
const content = useMemo(() => {
switch (activeTab as SidebarPanel | null) {
case "style":
return <StylePanel activeNodes={activeNodes} />;
case "base":
return <BaseStylePanel mindmap={mindmap} />;
case "theme":
return <ThemePanel mindmap={mindmap} />;
case "structure":
return <StructurePanel mindmap={mindmap} />;
case "icons":
return <IconPanel activeNodes={activeNodes} />;
case "outline":
return <OutlinePanel mindmap={mindmap} />;
case "settings":
return <SettingsPanel mindmap={mindmap} />;
case "formula":
return <FormulaPanel mindmap={mindmap} />;
case "note":
return <NotePanel mindmap={mindmap} />;
case "ai":
return <AiPanel />;
default:
return null;
}
}, [activeTab, mindmap, activeNodes]);
const title = useMemo(() => {
if (!activeTab) return "";
return sidebarTitles[activeTab as SidebarPanel] ?? "";
}, [activeTab]);
return (
<div
className={`absolute top-0 bottom-0 right-0 z-20 w-[300px] flex flex-col border-l border-gray-200 bg-white transition-transform duration-300 ease-in-out shadow-lg ${
activeTab ? "translate-x-0" : "translate-x-full"
}`}
>
<div className="flex items-center justify-between border-b px-4 py-3 shrink-0">
<span className="font-medium text-gray-700">{title}</span>
<button onClick={onClose} className="text-gray-400 hover:text-gray-600">
<X className="h-4 w-4" />
</button>
</div>
<div className="flex-1 overflow-y-auto px-4 py-4">
{content}
</div>
</div>
);
};