mind.tsx 13.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
import chatStyles from "@/app/components/chat.module.scss";
import homeStyles from "@/app/components/home.module.scss";

import { MindSiderBar } from "./mind-siderBar";
import MindElixir, {
  type Options,
  type MindElixirData,
  NodeObj,
} from "mind-elixir";
import { WindowContent } from "@/app/components/home";
import { useMobileScreen } from "@/app/utils";
import { IconButton } from "../button";
import Locale from "@/app/locales";
import { Path } from "@/app/constant";
import { useNavigate, useLocation } from "react-router-dom";
import clsx from "clsx";
import { getClientConfig } from "@/app/config/client";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useAppConfig } from "@/app/store";

import ReturnIcon from "@/app/icons/return.svg";
import MinIcon from "@/app/icons/min.svg";
import MaxIcon from "@/app/icons/max.svg";
import SDIcon from "@/app/icons/sd.svg";
import BoldIcon from "@/app/icons/bold.svg";
import FontColorIcon from "@/app/icons/fontColor.svg";
import FontBgIcon from "@/app/icons/fontBg.svg";
import CenterIcon from "@/app/icons/center.svg";
import MindIcon from "@/app/icons/mind.svg";
import LeftIcon from "@/app/icons/leftMind.svg";
import RightIcon from "@/app/icons/rightMind.svg";
import LineIcon from "@/app/icons/line.svg";
import InitSideIcon from "@/app/icons/initSide.svg";

import { useChatStore, useMindMapStore } from "@/app/store";
import {
  message,
  Select,
  ColorPicker,
  Button,
  Space,
  Slider,
  Popover,
} from "antd";
import type { ColorPickerProps, GetProp } from "antd";

import {
  INITIAL_DATA,
  LOADING_DATA,
  FONT_SIZE_OPTIONS,
  EXPORT_OPTIONS,
  useColor,
} from "./mind-utils";

type Color = Extract<
  GetProp<ColorPickerProps, "value">,
  string | { cleared: any }
>;
const ScaleControl = ({
  value,
  onChange,
}: {
  value: number;
  onChange: (v: number) => void;
}) => (
  <Slider
    vertical
    value={value}
    onChange={onChange}
    style={{ height: "100px" }}
    min={35}
    max={200}
    tooltip={{ formatter: (v) => `${v}%` }}
  />
);

export function MindPage() {
  const isMobileScreen = useMobileScreen();
  const navigate = useNavigate();
  const clientConfig = useMemo(() => getClientConfig(), []);
  const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  const config = useAppConfig();
  const scrollRef = useRef<HTMLDivElement>(null);
  const isMind = location.pathname === Path.Mind;
  const [isLoading, setIsLoading] = useState(false); //加载 辅助
  const containerRef = useRef<HTMLDivElement>(null); //思维导图容器
  const mindInstance = useRef<InstanceType<typeof MindElixir> | null>(null); //思维导图实例
  const chatStore = useChatStore();
  const { newMessages, content } = useMindMapStore.getState(); //聊天页面跳转时要生成的信息
  const query = useLocation();
  let { msg } = query.state || {};
  const [data, setData] = useState<MindElixirData>(INITIAL_DATA); //思维导图数据

  const [fontColor, setFontColor] = useColor("#1677ff"); //字体颜色
  const [nodeBgColor, setNodeBgColor] = useColor("#1677ff"); //节点背景颜色
  const [lineColor, setLinrColor] = useColor("#1677ff"); //分支颜色
  const [selectedNode, setSelectedNode] = useState<NodeObj | null>(null);
  const [scaleValue, setScaleValue] = useState(100);
  //如果是在聊天页面跳转过来时需要发起请求
  const fetchData = async () => {
    if (!msg) return;
    if (!content) return;
    setIsLoading(true);
    try {
      const response = await chatStore.getMindData(newMessages, "gpt-4o-mini");
      const cleanedContent = response.replace(/^```json|```$/g, "");
      const parsedData: MindElixirData = JSON.parse(cleanedContent);
      // 增强校验逻辑
      if (
        !parsedData?.nodeData?.id ||
        !Array.isArray(parsedData.nodeData.children)
      ) {
        throw new Error("数据结构不完整");
      }
      setData(parsedData);
      navigate(Path.Mind, { replace: true, state: { msg: null } });
    } catch (error) {
      console.log(error);
      message.error("请求失败,请重试");
    } finally {
      setIsLoading(false); // 确保关闭加载状态
    }
  };

  useEffect(() => {
    // 确保容器元素已挂载
    if (!containerRef.current) return;
    // 初始化配置项
    const options: Options = {
      el: containerRef.current,
      locale: "zh_CN",
      draggable: true,
      contextMenu: true,
      toolBar: false,
      nodeMenu: false,
    };
    // 创建实例
    mindInstance.current = new MindElixir(options);
    mindInstance.current.init(data);
    const el = mindInstance.current?.container.querySelector("me-root");
    //添加鼠标移入中心主题时鼠标变手的样式
    const style = document.createElement("style");
    // 添加 CSS 样式
    style.textContent = `
      me-root:hover {
        cursor: pointer;
      }
    `;
    // 将样式插入到文档中
    document.head.appendChild(style);

    const handleContainerClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      // 检查点击的目标是否是某个特定的元素(比如 me-root)
      if (target.closest("me-root")) {
        // 获取 me-nodes 父元素
        const parentElement = target.closest("me-nodes");
        // 确保父元素存在并且是 HTMLElement 类型
        if (parentElement && parentElement instanceof HTMLElement) {
          // 鼠标按下时开始跟随
          const onMouseDown = (e: MouseEvent) => {
            // 记录鼠标按下的初始位置和父元素的初始位置
            const initialX = e.clientX;
            const initialY = e.clientY;
            const initialElementX = parentElement.offsetLeft;
            const initialElementY = parentElement.offsetTop;
            // 鼠标移动时更新父元素位置
            const onMouseMove = (moveEvent: MouseEvent) => {
              const deltaX = moveEvent.clientX - initialX;
              const deltaY = moveEvent.clientY - initialY;
              parentElement.style.position = "absolute";
              parentElement.style.left = `${initialElementX + deltaX}px`;
              parentElement.style.top = `${initialElementY + deltaY}px`;
            };
            // 鼠标松开时停止跟随
            const onMouseUp = () => {
              window.removeEventListener("mousemove", onMouseMove);
              window.removeEventListener("mouseup", onMouseUp);
            };
            // 添加事件监听器
            window.addEventListener("mousemove", onMouseMove);
            window.addEventListener("mouseup", onMouseUp);
          };
          // 添加鼠标按下事件监听器
          target.addEventListener("mousedown", onMouseDown);
        }
      }
    };
    //注册点击事件
    mindInstance.current.container.addEventListener(
      "click",
      handleContainerClick,
    );
    fetchData();
    //设置选择的节点用于调节样式
    mindInstance.current?.bus.addListener("selectNode", (node) => {
      setSelectedNode(node);
    });

    return () => {
      mindInstance.current?.container.removeEventListener(
        "click",
        handleContainerClick,
      );
      if (mindInstance.current) {
        mindInstance.current.destroy();
        mindInstance.current = null;
      }
    };
  }, []);

  //data更新思维导图更新数据
  useEffect(() => {
    mindInstance.current?.refresh(data);
  }, [data]);

  useEffect(() => {
    if (isLoading) {
      mindInstance.current?.refresh(LOADING_DATA);
    }
  }, [isLoading]);

  useEffect(() => {
    if (selectedNode) {
      // 更新字体颜色
      updateNodeStyle({ color: fontColor });
    }
  }, [fontColor]);

  useEffect(() => {
    if (selectedNode) {
      // 更新节点背景颜色
      updateNodeStyle({ background: nodeBgColor });
    }
  }, [nodeBgColor]);
  // 导出函数
  const handleDownload = async (type: "png" | "svg") => {
    try {
      const blob =
        type === "png"
          ? await mindInstance.current?.exportPng(false)
          : await mindInstance.current?.exportSvg(false);

      if (!blob) return;

      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${data.nodeData.topic}.${type}`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error("导出失败:", error);
      message.error("导出失败,请重试");
    }
  };
  //思维导图缩放函数
  const handleScaleChange = (value: number) => {
    setScaleValue(value);
    mindInstance.current?.scale(value / 100);
  };
  //更新样式
  const updateNodeStyle = (style: Partial<NodeObj["style"]>) => {
    if (selectedNode) {
      mindInstance.current?.reshapeNode(MindElixir.E(selectedNode.id), {
        style: { ...selectedNode.style, ...style },
      });
    }
  };
  //更新分支颜色
  const updateBranchColor = (value: string) => {
    if (selectedNode) {
      mindInstance.current?.reshapeNode(MindElixir.E(selectedNode.id), {
        branchColor: value,
      });
    }
  };

  const mindType = (
    <div>
      <Button
        icon={<LeftIcon />}
        onClick={() => {
          mindInstance.current?.initLeft();
        }}
      />
      <Button
        icon={<RightIcon />}
        onClick={() => {
          mindInstance.current?.initRight();
        }}
      />
      <Button
        icon={
          <InitSideIcon
            onClick={() => {
              mindInstance.current?.initSide();
            }}
          />
        }
      />
    </div>
  );
  //工具栏
  const renderToolbar = () => (
    <Space>
      <Popover
        content={
          <ScaleControl value={scaleValue} onChange={handleScaleChange} />
        }
      >
        <Button>{scaleValue}%</Button>
      </Popover>
      <Popover content={mindType}>
        <Button icon={<MindIcon />}></Button>
      </Popover>
      <Select
        options={EXPORT_OPTIONS}
        onSelect={handleDownload}
        placeholder="导出"
        style={{ width: 120 }}
      />

      <Select
        options={FONT_SIZE_OPTIONS}
        onSelect={(v) => updateNodeStyle({ fontSize: v })}
        placeholder="字号"
        style={{ width: 100 }}
        disabled={!selectedNode}
      />

      <Button
        icon={<CenterIcon />}
        onClick={() => mindInstance.current?.toCenter()}
      />

      <Button
        icon={<BoldIcon />}
        onClick={() =>
          updateNodeStyle({
            fontWeight:
              selectedNode?.style?.fontWeight === "bold" ? "normal" : "bold",
          })
        }
        disabled={!selectedNode}
      />
      <ColorPicker
        value={fontColor}
        onChange={(value) => {
          setFontColor(value || "#000000"); // 处理可能的空值
          updateNodeStyle({ color: value?.toHexString() || "#000000" });
        }}
        disabled={!selectedNode}
        showText
      >
        <Button icon={<FontColorIcon />} />
      </ColorPicker>

      <ColorPicker
        value={nodeBgColor}
        onChange={(value) => {
          setNodeBgColor(value || "#ffffff");
          updateNodeStyle({ background: value?.toHexString() || "#ffffff" });
        }}
        disabled={!selectedNode}
        showText
      >
        <Button icon={<FontBgIcon />} />
      </ColorPicker>

      <ColorPicker
        value={lineColor}
        onChange={(value) => {
          setLinrColor(value || "#ffffff");
          updateBranchColor(value?.toHexString() || "#ffffff");
        }}
        disabled={!selectedNode}
        showText
      >
        <Button icon={<LineIcon />} />
      </ColorPicker>
    </Space>
  );

  return (
    <>
      <MindSiderBar
        className={clsx({ [homeStyles["sidebar-show"]]: isMind })}
        setData={setData}
        isLoading={isLoading}
        setIsLoading={setIsLoading}
      />
      <WindowContent>
        <div className={chatStyles.chat} key={"1"}>
          <div className="window-header" data-tauri-drag-region>
            {isMobileScreen && (
              <div className="window-actions">
                <div className={"window-action-button"}>
                  <IconButton
                    icon={<ReturnIcon />}
                    bordered
                    title={Locale.Chat.Actions.ChatList}
                    onClick={() => navigate(Path.BgRemoval)}
                  />
                </div>
              </div>
            )}
            <div
              className={clsx(
                "window-header-title",
                chatStyles["chat-body-title"],
              )}
            >
              <div className={`window-header-main-title`}>生成思维导图</div>
            </div>
            <div className={chatStyles["chat-message-actions"]}>
              <div className={chatStyles["chat-input-actions"]}>
                {renderToolbar()}
              </div>
            </div>
            <div className="window-actions">
              {showMaxIcon && (
                <div className="window-action-button">
                  <IconButton
                    aria={Locale.Chat.Actions.FullScreen}
                    icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
                    bordered
                    onClick={() => {
                      config.update(
                        (config) => (config.tightBorder = !config.tightBorder),
                      );
                    }}
                  />
                </div>
              )}
              {isMobileScreen && <SDIcon width={50} height={50} />}
            </div>
          </div>
          <div className={chatStyles["chat-body"]} ref={scrollRef}>
            <div ref={containerRef} style={{ width: "100%", height: "100%" }} />
          </div>
        </div>
      </WindowContent>
    </>
  );
}