Ver código fonte

fix: 修复思维导图卡顿、新增编辑状态问题

liaojiaxing 1 semana atrás
pai
commit
ac19ad16f0

+ 9 - 10
apps/designer/src/components/mindMap/Border.tsx

@@ -25,19 +25,18 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
   // 删除边框
   const handleRemove = () => {
     const parentNode = graph.getCellById(origin);
-    parentNode?.setData(
-      {
-        border: undefined,
-      },
-      {
-        deep: false,
-      }
-    );
+    parentNode?.prop('changeNodeData', {
+      cellId: parentNode.id,
+      data: { border: undefined },
+      ignoreRender: false
+    });
   };
 
   const handleChange = (key: string, value: any) => {
-    node.setData({
-      [key]: value,
+    node.prop('changeNodeData', {
+      cellId: node.id,
+      data: { [key]: value },
+      ignoreRender: false
     });
   };
 

+ 36 - 22
apps/designer/src/components/mindMap/ExtraModule.tsx

@@ -9,21 +9,27 @@ export default function ExtraModule({
   extraModules: { type: "image" | "code"; data: Record<string, any> };
 }) {
   const handleChange = (key: string, value: number) => {
-    node.setData({
-      extraModules: {
-        ...extraModules,
-        data: {
-          ...extraModules.data,
-          [key]: value,
+    node.prop("changeNodeData", {
+      cellId: node.id,
+      data: {
+        extraModules: {
+          ...extraModules,
+          data: {
+            ...extraModules.data,
+            [key]: value,
+          },
         },
       },
+      ignoreRender: false,
     });
   };
   const handleDelete = () => {
-    node.setData({
-      extraModules: undefined,
-    }, {
-      deep: false
+    node.prop("changeNodeData", {
+      cellId: node.id,
+      data: {
+        extraModules: undefined,
+      },
+      ignoreRender: false,
     });
   };
   return extraModules.type === "code" ? (
@@ -34,25 +40,33 @@ export default function ExtraModule({
         code={extraModules.data.code}
         language={extraModules.data.language}
         onChange={(code: string) => {
-          node.setData({
-            extraModules: {
-              type: "code",
-              data: {
-                code,
-                language: extraModules.data.language,
+          node.prop("changeNodeData", {
+            cellId: node.id,
+            data: {
+              extraModules: {
+                type: "code",
+                data: {
+                  code,
+                  language: extraModules.data.language,
+                },
               },
             },
+            ignoreRender: false,
           });
         }}
         onLanguageChange={(language: string) => {
-          node.setData({
-            extraModules: {
-              type: "code",
-              data: {
-                code: extraModules.data.code,
-                language,
+          node.prop("changeNodeData", {
+            cellId: node.id,
+            data: {
+              extraModules: {
+                type: "code",
+                data: {
+                  code: extraModules.data.code,
+                  language,
+                },
               },
             },
+            ignoreRender: false,
           });
         }}
         onDelete={handleDelete}

+ 42 - 31
apps/designer/src/components/mindMap/SummaryBorder.tsx

@@ -13,7 +13,7 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
   const handleResizeChange = () => {
     setWidth(node.size().width);
     setHeight(node.size().height);
-  }
+  };
 
   useEffect(() => {
     const handleSelect = (args: EventArgs["node:selected"]) => {
@@ -35,23 +35,23 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
       const x = originNode.position().x + originNode.size().width / 2;
       const y = originNode.position().y + originNode.size().height / 2;
       if (
-        x < node.position().x 
-        && y > node.position().y
-        && y < node.position().y + height
+        x < node.position().x &&
+        y > node.position().y &&
+        y < node.position().y + height
       ) {
         return "left";
       }
       if (
-        y > node.position().y
-        && x > node.position().x
-        && x < node.position().x + width
+        y > node.position().y &&
+        x > node.position().x &&
+        x < node.position().x + width
       ) {
         return "bottom";
       }
       if (
-        y < node.position().y
-        && x > node.position().x
-        && x < node.position().x + width
+        y < node.position().y &&
+        x > node.position().x &&
+        x < node.position().x + width
       ) {
         return "top";
       }
@@ -181,41 +181,52 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
   }, [type, width, height]);
 
   const path = useMemo(() => {
-    switch(linePosition) {
-      case 'bottom': return bottomLine;
-      case 'top': return topLine;
-      case 'left': return leftLine;
-      case 'right': return rightLine;
+    switch (linePosition) {
+      case "bottom":
+        return bottomLine;
+      case "top":
+        return topLine;
+      case "left":
+        return leftLine;
+      case "right":
+        return rightLine;
     }
   }, [type, width, height]);
 
   // 删除概要
   const handleRemove = () => {
     const parentNode = graph.getCellById(summarySource);
-    parentNode?.setData(
-      {
+    parentNode?.prop("changeNodeData", {
+      cellId: parentNode.id,
+      data: {
         summary: undefined,
       },
-      {
-        deep: false,
-      }
-    );
+      ignoreRender: false,
+    });
   };
 
   const handleChange = (key: string, value: any) => {
-    node.setData({
-      [key]: value,
+    node.prop("changeNodeData", {
+      cellId: node.id,
+      data: {
+        [key]: value,
+      },
+      ignoreRender: false,
     });
     const parentNode = graph.getCellById(summarySource);
     if (parentNode) {
-      parentNode.setData({
-        summary: {
-          ...parentNode.data.summary,
-          border: {
-            ...parentNode.data.summary.border,
-            [key]: value,
+      parentNode.prop("changeNodeData", {
+        cellId: parentNode.id,
+        data: {
+          summary: {
+            ...parentNode.data.summary,
+            border: {
+              ...parentNode.data.summary.border,
+              [key]: value,
+            },
           },
         },
+        ignoreRender: false,
       });
     }
   };
@@ -370,9 +381,9 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
           >
             <i
               className="z-9 iconfont icon-more text-12px absolute top-25% cursor-pointer"
-              style={{ 
+              style={{
                 color: line.color || "#000",
-                [linePosition]: '-36px'
+                [linePosition]: "-36px",
               }}
             />
           </Popover>

+ 24 - 16
apps/designer/src/components/mindMap/Text.tsx

@@ -17,6 +17,11 @@ export default function Text(props: {
   const { value, styles, node, placeholder, txtStyle } = props;
   const [isEditing, setIsEditing] = useSafeState(false);
   const inputRef = useRef<InputRef>(null);
+  const [labelText, setLabelText] = useState(value);
+
+  useEffect(() => {
+    setLabelText(value);
+  }, [value]);
 
   const style = useMemo((): React.CSSProperties => {
     return {
@@ -30,7 +35,8 @@ export default function Text(props: {
   }, [styles]);
 
   const handleChange = (val: string) => {
-    node.setData({ label: val });
+    // node.setData({ label: val });
+    setLabelText(val);
     props.onChange?.(val);
   };
 
@@ -39,12 +45,23 @@ export default function Text(props: {
       return;
     }
     node.setData({
-      ignoreDrag: edit,
+      ignoreDrag: edit
     });
     if (edit) {
+      // 置顶
+      node.toFront();
       setTimeout(() => {
         inputRef.current?.focus({ cursor: "all" });
       }, 100);
+    } else {
+      // 更新数据
+      node.prop("changeNodeData", {
+        cellId: node.id,
+        data: {
+          label: labelText
+        },
+        ignoreRender: false,
+      });
     }
     setIsEditing(edit);
   };
@@ -91,9 +108,7 @@ export default function Text(props: {
 
   const handleReplace = (args: any) => {
     const { type, searchText, replaceText, currentIndex, currentCellId } = args?.current || {};
-    // if(args.current?.type === 'replaceAll') {
-    //   handleChange(value.replaceAll(searchText, replaceText));
-    // }
+    // 单个替换  全部替换不在此实现
     if(type === 'replace' && currentCellId === node.id) {
       const list = value.split(searchText);
       const text = list.map((str, index) => {
@@ -112,27 +127,20 @@ export default function Text(props: {
     node.off("change:find", handleFind);
     node.off("change:replace", handleReplace);
     node.off("change:clearFind", handleClear);
+    node.off("change:customEdit", handleSetEditing);
 
     node.on("change:find", handleFind);
     node.on("change:replace", handleReplace);
     node.on("change:clearFind", handleClear);
+    node.on("change:customEdit", handleSetEditing);
     return () => {
       node.off("change:find", handleFind);
       node.off("change:replace", handleReplace);
       node.off("change:clearFind", handleClear);
+      node.off("change:customEdit", handleSetEditing);
     };
   }, [value]);
 
-  // useEffect(() => {
-  //   // 处理字体加载
-  //   // @ts-ignore
-  //   // WebFont.load({
-  //   //   google: {
-  //   //     families: [styles.fontFamily]
-  //   //   }
-  //   // })
-  // }, [styles.fontFamily]);
-
   return (
     <div style={txtStyle}>
       <div
@@ -148,7 +156,7 @@ export default function Text(props: {
         <Input.TextArea
           ref={inputRef}
           placeholder={placeholder}
-          value={value}
+          value={labelText}
           variant="borderless"
           style={{
             ...style,

+ 109 - 65
apps/designer/src/components/mindMap/Topic.tsx

@@ -35,7 +35,7 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
     collapsed,
     fixedWidth,
     linkTopicId,
-    parentId
+    parentId,
   } = node.getData();
   const { size, ref } = useSizeHook();
   const { fillContent, strokeColor, strokeWidth } = useShapeProps(
@@ -76,19 +76,19 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
     }
   }, [type]);
 
-  type Position = 'right' | 'left' | 'top' | 'bottom';
+  type Position = "right" | "left" | "top" | "bottom";
   // 折叠按钮位置
-  const collapsedPosition = useMemo(() => { 
-    let position: Position = 'right';
+  const collapsedPosition = useMemo(() => {
+    let position: Position = "right";
     const parentNode = graph.getCellById(parentId);
     if (parentNode?.isNode()) {
       const { x, y } = parentNode?.getPosition() || { x: 0, y: 0 };
-      const { x: x1, y: y1} = node.getPosition();
-      if(x1 < x) {
-        position = 'left';
+      const { x: x1, y: y1 } = node.getPosition();
+      if (x1 < x) {
+        position = "left";
       }
     }
-    
+
     return position;
   }, [parentId, node.getAttrs()]);
 
@@ -101,20 +101,26 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
         onCancel={() => setShowPopover(false)}
         onConfirm={(data) => {
           setShowPopover(false);
-          node.setData({ href: data });
+          // node.setData({ href: data });
+          node.prop("changeNodeData", {
+            cellId: node.id,
+            data: { href: data },
+            ignoreRender: true,
+          });
         }}
       />
     );
   };
 
   // @ts-ignore 绑定一个外部调用方法
-  node.extendAttr = {
-    showHrefConfig,
-  };
+  if (!node.extendAttr) {
+    // @ts-ignore
+    node.extendAttr = {
+      showHrefConfig,
+    };
+  }
 
   useEffect(() => {
-    // graph.createTransformWidget(node);
-    // graph.select(node);
     graph.on("node:selected", handleSelect);
     graph.on("node:unselected", handleSelect);
     return () => {
@@ -131,9 +137,13 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
       (size.width !== clientWidth || size.height !== clientHeight)
     ) {
       node.size(clientWidth, clientHeight);
-      node.setData({
-        width: clientWidth,
-        height: clientHeight,
+      node.prop("changeNodeData", {
+        cellId: node.id,
+        data: {
+          width: clientWidth,
+          height: clientHeight,
+        },
+        ignoreRender: false,
       });
     }
   };
@@ -180,46 +190,58 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
   };
 
   const handleToggleCollapse = () => {
-    node.setData({
-      collapsed: !collapsed,
+    node.prop("changeNodeData", {
+      cellId: node.id,
+      data: {
+        collapsed: !collapsed,
+      },
+      ignoreRender: false,
     });
   };
 
   const handleDeleteHeft = () => {
-    node.setData(
-      {
+    node.prop("changeNodeData", {
+      cellId: node.id,
+      data: {
         href: undefined,
       },
-      {
-        deep: false,
-      }
-    );
+      ignoreRender: false,
+    });
   };
 
-  const handleChangeTag = (tagInfo: { color?: string; title?: string }, index: number) => {
-    node.setData({
-      tags: tags.map((item: { color?: string; title?: string }, i: number) => {
-        if (index === i) {
-          return {
-            ...item,
-            ...tagInfo
+  const handleChangeTag = (
+    tagInfo: { color?: string; title?: string },
+    index: number
+  ) => {
+    node.prop("changeNodeData", {
+      cellId: node.id,
+      data: {
+        tags: tags.map(
+          (item: { color?: string; title?: string }, i: number) => {
+            if (index === i) {
+              return {
+                ...item,
+                ...tagInfo,
+              };
+            }
+            return item;
           }
-        }
-        return item;
-      }, {
-        deep: false
-      })
-    })
-  }
+        ),
+      },
+      ignoreRender: false,
+    });
+  };
 
   const handleDeleteTag = (index: number) => {
     tags.splice(index, 1);
-    node.setData({
-      tags
-    }, {
-      deep: false
+    node.prop("changeNodeData", {
+      cellId: node.id,
+      data: {
+        tags,
+      },
+      ignoreRender: false,
     });
-  }
+  };
 
   return (
     <div>
@@ -250,7 +272,7 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
           onMouseOver={() => !collapsed && setShowCollapsePoint(true)}
           onMouseLeave={() => !collapsed && setShowCollapsePoint(false)}
         >
-          <FlowExtra node={node}/>
+          <FlowExtra node={node} />
           {/* 扩展模块 */}
           {extraModules && (
             <div className="extra" ref={extraModuleRef}>
@@ -275,6 +297,7 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
               fixedWidth={fixedWidth}
               styles={{
                 ...text,
+                background: fillContent,
               }}
               txtStyle={{
                 position: "relative",
@@ -295,7 +318,12 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
                 />
               )}
               {remark && (
-                <Tooltip color="#ffffdd" title={<span className="color-#333">{remark}</span>} autoAdjustOverflow trigger={['hover', 'click']}>
+                <Tooltip
+                  color="#ffffdd"
+                  title={<span className="color-#333">{remark}</span>}
+                  autoAdjustOverflow
+                  trigger={["hover", "click"]}
+                >
                   <i
                     className="iconfont icon-pinglun1 cursor-pointer ml-4px"
                     onClick={handleShowRemark}
@@ -314,21 +342,23 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
           </div>
           {/* 标签 */}
           <div className="" ref={tagRef}>
-            {tags?.map((item: { name: string; color: string }, index: number) => {
-              return (
-                <CustomTag
-                  className="text-14px inline-block mr-8px"
-                  key={item.name}
-                  title={item.name}
-                  color={item.color}
-                  onChangeTag={(tag) => handleChangeTag(tag, index)}
-                  onDelete={() => handleDeleteTag(index)}
-                  hideEditBtn
-                >
-                  {item.name}
-                </CustomTag>
-              );
-            })}
+            {tags?.map(
+              (item: { name: string; color: string }, index: number) => {
+                return (
+                  <CustomTag
+                    className="text-14px inline-block mr-8px"
+                    key={item.name}
+                    title={item.name}
+                    color={item.color}
+                    onChangeTag={(tag) => handleChangeTag(tag, index)}
+                    onDelete={() => handleDeleteTag(index)}
+                    hideEditBtn
+                  >
+                    {item.name}
+                  </CustomTag>
+                );
+              }
+            )}
           </div>
 
           {/* 添加主题按钮 */}
@@ -352,7 +382,9 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
               hover:bg-#067bef 
               hover:color-white`}
               onClick={handleAddBranch}
-              style={collapsedPosition === 'left' ? {left: -25} : {right: -25}}
+              style={
+                collapsedPosition === "left" ? { left: -25 } : { right: -25 }
+              }
             >
               <PlusOutlined />
             </div>
@@ -362,7 +394,9 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
           {type !== TopicType.main && children.length && (
             <div
               className="absolute right--30px top-0 w-30px h-full"
-              style={collapsedPosition === 'left' ? { left: -30 } : { right: -30 }}
+              style={
+                collapsedPosition === "left" ? { left: -30 } : { right: -30 }
+              }
               onMouseOver={() => !collapsed && setShowCollapsePoint(true)}
               onMouseOut={() => !collapsed && setShowCollapsePoint(false)}
             />
@@ -390,8 +424,18 @@ const component = ({ node, graph }: { node: Node; graph: Graph }) => {
               style={{
                 border: `1px solid ${fill.color1}`,
                 color: fill.color1,
-                right: collapsedPosition === 'right' ? collapsed ? -20 : -15 : 'auto',
-                left: collapsedPosition === 'left' ? collapsed ? -20 : -15 : 'auto',
+                right:
+                  collapsedPosition === "right"
+                    ? collapsed
+                      ? -20
+                      : -15
+                    : "auto",
+                left:
+                  collapsedPosition === "left"
+                    ? collapsed
+                      ? -20
+                      : -15
+                    : "auto",
               }}
             >
               {collapsed && childrenCount}

+ 20 - 13
apps/designer/src/pages/mindmap/components/Config/NodeStyle.tsx

@@ -13,8 +13,10 @@ import { ImageFillType, BorderSize, TopicType } from "@/enum";
 import { set, cloneDeep } from "lodash-es";
 import { Cell } from "@antv/x6";
 import { fontFamilyOptions } from "@/pages/flow/data";
+import { updateTopic } from "../../render";
+
 export default function GraphStyle() {
-  const { selectedCell } = useModel("mindmap.mindMapModel");
+  const { selectedCell, setMindProjectInfo } = useModel("mindmap.mindMapModel");
   const eventNodeList = useRef<Cell[]>([]);
 
   const [formModel, setFormModel] = useState({
@@ -73,8 +75,8 @@ export default function GraphStyle() {
         isStroke: data.stroke.width > 0,
         stroke: {
           ...data.stroke,
-          width: data.stroke.width || 1
-        }
+          width: data.stroke.width || 1,
+        },
       });
 
       // 监听当前选中节点的属性变化
@@ -122,20 +124,21 @@ export default function GraphStyle() {
     selectedCell?.forEach((cell) => {
       if (cell.isNode()) {
         model.fixedWidth && cell.setSize(model.width, cell.size().height);
-        cell.setData({
+        const updateData = {
           text: model.text,
           edge: model.edge,
           borderSize: model.borderSize,
           fixedWidth: model.fixedWidth,
           fill: {
             ...model.fill,
-            color1: model.isFill ? model.fill.color1 : "transparent"
+            color1: model.isFill ? model.fill.color1 : "transparent",
           },
           stroke: {
             ...model.stroke,
-            width: model.isStroke ? model.stroke.width : 0
+            width: model.isStroke ? model.stroke.width : 0,
           },
-        });
+        };
+        updateTopic(cell.id, updateData as any, setMindProjectInfo);
       }
     });
   };
@@ -212,7 +215,7 @@ export default function GraphStyle() {
             min={12}
             max={10000}
             formatter={(val) => `${val}px`}
-            parser={(val) => Number(val?.replace('px', ''))}
+            parser={(val) => Number(val?.replace("px", ""))}
             disabled={!formModel.fixedWidth}
             value={formModel.width}
             onChange={(val) => handleSetFormModel("width", val)}
@@ -245,7 +248,7 @@ export default function GraphStyle() {
             min={12}
             max={10000}
             formatter={(val) => `${val}px`}
-            parser={(val) => Number(val?.replace('px', ''))}
+            parser={(val) => Number(val?.replace("px", ""))}
             disabled={!selectedCell?.length}
             value={formModel.text.fontSize}
             onChange={(val) => handleSetFormModel("text.fontSize", val)}
@@ -370,7 +373,7 @@ export default function GraphStyle() {
             min={1}
             max={10}
             formatter={(val) => `${val}px`}
-            parser={(val) => Number(val?.replace('px', ''))}
+            parser={(val) => Number(val?.replace("px", ""))}
             disabled={!formModel.isStroke}
             value={formModel.stroke.width}
             onChange={(val) => handleSetFormModel("stroke.width", val)}
@@ -410,7 +413,9 @@ export default function GraphStyle() {
         <div className="flex items-center justify-between mb-8px">
           <div className="font-bold mb-8px">连线</div>
           <CustomColorPicker
-            disabled={!selectedCell?.length || formModel.type === TopicType.main}
+            disabled={
+              !selectedCell?.length || formModel.type === TopicType.main
+            }
             color={formModel.edge.color}
             onChange={(color) => handleSetFormModel("edge.color", color)}
           />
@@ -422,8 +427,10 @@ export default function GraphStyle() {
             min={1}
             max={10}
             formatter={(val) => `${val}px`}
-            parser={(val) => Number(val?.replace('px', ''))}
-            disabled={!selectedCell?.length || formModel.type === TopicType.main}
+            parser={(val) => Number(val?.replace("px", ""))}
+            disabled={
+              !selectedCell?.length || formModel.type === TopicType.main
+            }
             value={formModel.edge.width}
             onChange={(val) => handleSetFormModel("edge.width", val)}
           />

+ 3 - 1
apps/designer/src/pages/mindmap/fastKey.tsx

@@ -46,7 +46,9 @@ export const bindMindmapKeys = (
     e.preventDefault();
     const topicIds = graph
       .getSelectedCells()
-      .filter((cell) => cell.isNode)
+      .filter((cell) => {
+        return cell.isNode() && !(cell.data?.ignoreDrag || cell.data?.lock )
+      })
       .map((cell) => cell.id);
     deleteTopics(topicIds, graph, setMindProjectInfo);
   });

+ 12 - 5
apps/designer/src/pages/mindmap/models/mindMapModel.ts

@@ -63,6 +63,7 @@ export default function mindMapModel() {
   const projectInfoRef = useRef<MindMapProjectInfo>();
   const timer = useRef<any>();
   const settingTimer = useRef<any>();
+  const canLoadHistory = useRef(false); // 能否加载历史记录
   // 历史记录
   const {
     value: historyValue,
@@ -97,6 +98,7 @@ export default function mindMapModel() {
     console.log("init:", init);
     console.log("ignoreRender:", ignoreRender);
     console.log("ignoreHistory:", ignoreHistory);
+    canLoadHistory.current = false;
     if (isEqual(info, projectInfoRef.current)) {
       return;
     }
@@ -187,10 +189,13 @@ export default function mindMapModel() {
 
 
   useEffect(() => {
-    historyValue && setMindProjectInfo({
-      info: historyValue,
-      ignoreHistory: true
-    })
+    // 加载历史记录数据 根据撤销重做加载
+    if (historyValue && canLoadHistory.current) {
+      setMindProjectInfo({
+        info: historyValue,
+        ignoreHistory: true
+      });
+    }
   }, [historyValue]);
 
   const pageSettingRef = useRef<MindMapProjectInfo["pageSetting"]>();
@@ -214,7 +219,7 @@ export default function mindMapModel() {
           repeat: "repeat",
         });
       }
-      console.log(pageSetting)
+
       // 设置水印
       if (pageSetting.showWatermark && pageSetting.watermarkText) {
         const canvas = document.createElement("canvas");
@@ -365,11 +370,13 @@ export default function mindMapModel() {
 
   // 撤销
   const onUndo = () => {
+    canLoadHistory.current = true;
     back();
   };
 
   // 重做
   const onRedo = () => {
+    canLoadHistory.current = true;
     forward();
   };
 

+ 114 - 89
apps/designer/src/pages/mindmap/render/index.tsx

@@ -10,7 +10,10 @@ import { hierarchyMethodMap } from "./hierarchy";
 import { createEdge } from "./edge";
 import { getTheme } from "./theme";
 import { topicMenu } from "@/utils/contentMenu";
-import { cacluculateExtremeValue, getBorderPositionAndSize } from "../mindmapHander";
+import {
+  cacluculateExtremeValue,
+  getBorderPositionAndSize,
+} from "../mindmapHander";
 import { useMindMapStore } from "../models/mindMapModel";
 import { cloneDeep } from "lodash-es";
 
@@ -23,7 +26,7 @@ type RenderParams = {
   setMindProjectInfo?: (data: any) => void;
   returnCells?: boolean;
   showTool?: boolean;
-}
+};
 
 /**
  * 渲染思维导图项目
@@ -37,7 +40,7 @@ export const renderMindMap = ({
   graph,
   setMindProjectInfo,
   returnCells = false,
-  showTool = true
+  showTool = true,
 }: RenderParams) => {
   const cells: Cell[] = [];
   topics.forEach((topic) => {
@@ -73,14 +76,16 @@ export const renderMindMap = ({
           id,
           x: offsetX + x,
           y: offsetY + y,
-          tools: showTool ? [
-            {
-              name: "contextmenu",
-              args: {
-                menu: topicMenu,
-              },
-            },
-          ] : [],
+          tools: showTool
+            ? [
+                {
+                  name: "contextmenu",
+                  args: {
+                    menu: topicMenu,
+                  },
+                },
+              ]
+            : [],
         });
         // 渲染边框
         if (data.border) {
@@ -99,7 +104,7 @@ export const renderMindMap = ({
             graph,
             offsetX,
             offsetY,
-            setMindProjectInfo,
+            setMindProjectInfo
           );
           cells.push(...(summaryCells || []));
         }
@@ -118,7 +123,7 @@ export const renderMindMap = ({
             if (!isBracket || index === 0 || index === children.length - 1) {
               const edge = createEdge(graph, id, item, structure, theme, {
                 onlyOneChild: children.length === 1,
-                direction: item?.direction
+                direction: item?.direction,
               });
               cells.push(edge);
               node.addChild(edge);
@@ -134,7 +139,7 @@ export const renderMindMap = ({
   });
 
   // 数据为概要节点 返回节点数据
-  if(returnCells) {
+  if (returnCells) {
     return cells;
   }
 
@@ -167,7 +172,7 @@ export const renderMindMap = ({
     if (data?.parentId) {
       const parent = graph.getCellById(data.parentId);
       const child = graph.getCellById(cell.id);
-      if(parent && child && !child.hasParent()) {
+      if (parent && child && !child.hasParent()) {
         parent.removeChild(child);
         parent.addChild(child);
       }
@@ -182,15 +187,15 @@ export const renderMindMap = ({
 
 // 渲染概要
 const createSummaryCells = (
-  hierarchyItem: HierarchyResult, 
-  summary: TopicItem['summary'],
+  hierarchyItem: HierarchyResult,
+  summary: TopicItem["summary"],
   structure: StructureType,
-  pageSetting: MindMapProjectInfo['pageSetting'],
+  pageSetting: MindMapProjectInfo["pageSetting"],
   theme: string,
   graph: Graph,
   offsetX: number,
   offsetY: number,
-  setMindProjectInfo?: (data: any) => void,
+  setMindProjectInfo?: (data: any) => void
 ): Cell[] => {
   let cells: Cell[] = [];
   if (summary) {
@@ -220,36 +225,45 @@ const createSummaryCells = (
 
     let position = {
       x: offsetX + hierarchyItem.x + totalWidth + 40,
-      y: offsetY + hierarchyItem.y
-    }
+      y: offsetY + hierarchyItem.y,
+    };
 
-    if(
-      [StructureType.left, StructureType.leftBracket, StructureType.leftFishbone, StructureType.leftTreeShape].includes(structure)
-      || structure === StructureType.leftRight && hierarchyItem.direction === 'left'
+    if (
+      [
+        StructureType.left,
+        StructureType.leftBracket,
+        StructureType.leftFishbone,
+        StructureType.leftTreeShape,
+      ].includes(structure) ||
+      (structure === StructureType.leftRight &&
+        hierarchyItem.direction === "left")
     ) {
       position = {
         x: offsetX + hierarchyItem.x - 40 - totalWidth,
-        y: offsetY + hierarchyItem.y
-      }
+        y: offsetY + hierarchyItem.y,
+      };
     }
-    const list = renderMindMap({
-      topics: [{
-        ...summary.topic,
-        ...position
-      }],
-      pageSetting,
-      structure,
-      theme,
-      graph,
-      setMindProjectInfo,
-      returnCells: true
-    }) || [];
+    const list =
+      renderMindMap({
+        topics: [
+          {
+            ...summary.topic,
+            ...position,
+          },
+        ],
+        pageSetting,
+        structure,
+        theme,
+        graph,
+        setMindProjectInfo,
+        returnCells: true,
+      }) || [];
 
     // 概要节点
     cells.push(...list);
   }
   return cells;
-}
+};
 
 // 创建外框组件
 const createBorderComponent = (
@@ -282,10 +296,11 @@ const createBorderComponent = (
 const updateNode = (node: Node, graph: Graph) => {
   const oldCell = graph.getCellById(node.id);
   if (oldCell.isNode()) {
+    const { width, height } = node.size();
     oldCell.setData(node.data, { silent: false, deep: false });
     const p = node.position();
-    oldCell.setPosition(p)
-    oldCell.setSize(node.size().width, node.size().height);
+    oldCell.setPosition(p);
+    oldCell.setSize(width, height);
   }
 };
 
@@ -299,7 +314,9 @@ export const addTopic = (
   parentNode?: Node,
   otherData: Record<string, any> = {}
 ): TopicItem | undefined => {
-  const projectInfo: MindMapProjectInfo = cloneDeep(useMindMapStore.getState().mindProjectInfo);
+  const projectInfo: MindMapProjectInfo = cloneDeep(
+    useMindMapStore.getState().mindProjectInfo
+  );
   if (!projectInfo || !setMindProjectInfo) return;
   // 构造主题节点
   const topic = buildTopic(
@@ -308,7 +325,7 @@ export const addTopic = (
       ...(otherData || {}),
       parentId: parentNode?.id,
       isSummary: parentNode?.data?.isSummary,
-      summarySource: parentNode?.data?.summarySource
+      summarySource: parentNode?.data?.summarySource,
     },
     graph,
     parentNode
@@ -330,7 +347,7 @@ export const addTopic = (
           traverse(item.children);
         }
         if (item.summary) {
-          traverse([item.summary.topic])
+          traverse([item.summary.topic]);
         }
       });
     };
@@ -340,8 +357,16 @@ export const addTopic = (
     projectInfo.topics.push(topic);
   }
 
-  setMindProjectInfo({info: projectInfo});
-  
+  setMindProjectInfo({ info: projectInfo });
+  // 进入编辑模式
+  if (parentNode) {
+    setTimeout(() => {
+      const newTopicNode = graph.getCellById(topic.id);
+      if (newTopicNode) {
+        newTopicNode.prop("customEdit", true);
+      }
+    }, 100);
+  }
   return topic;
 };
 
@@ -377,14 +402,16 @@ export const buildTopic = (
   graph?: Graph,
   parentNode?: Node
 ): TopicItem => {
-  const projectInfo: MindMapProjectInfo = cloneDeep(useMindMapStore.getState().mindProjectInfo);
+  const projectInfo: MindMapProjectInfo = cloneDeep(
+    useMindMapStore.getState().mindProjectInfo
+  );
 
   const theme = getTheme(
-    projectInfo?.theme || 'default',
+    projectInfo?.theme || "default",
     type === TopicType.sub ? parentNode?.data : undefined
   );
   const id = uuid();
-  return  {
+  return {
     ...topicData,
     id,
     type,
@@ -444,53 +471,51 @@ export const updateTopic = (
   };
 
   traverse(projectInfo?.topics || []);
-  setMindProjectInfo({info: projectInfo});
+  setMindProjectInfo({ info: projectInfo });
 };
 
 /**
  * 根据ai数据返回思维导图主题
- * @param data 
- * @param parentId 
- * @param type 
- * @param parentTopic 
- * @param graph 
- * @returns 
+ * @param data
+ * @param parentId
+ * @param type
+ * @param parentTopic
+ * @param graph
+ * @returns
  */
 export const getTopicsByAiData = (
-    data: any[],
-    parentId: string,
-    type: TopicType,
-    parentTopic: TopicItem,
-    graph?: Graph
-  ) => {
-    const ids: string[] = [];
-    data = Array.isArray(data) ? data : [data];
-    const topics = data?.map((item) => {
-      const topic = buildTopic(
-        type,
-        { id: item.id, label: item.label },
-        graph,
-        { id: parentId, data: parentTopic } as Node
+  data: any[],
+  parentId: string,
+  type: TopicType,
+  parentTopic: TopicItem,
+  graph?: Graph
+) => {
+  const ids: string[] = [];
+  data = Array.isArray(data) ? data : [data];
+  const topics = data?.map((item) => {
+    const topic = buildTopic(type, { id: item.id, label: item.label }, graph, {
+      id: parentId,
+      data: parentTopic,
+    } as Node);
+    topic.parentId = parentId;
+    ids.push(topic.id);
+    if (item.children) {
+      const child = getTopicsByAiData(
+        item.children,
+        topic.id,
+        TopicType.sub,
+        topic,
+        graph
       );
-      topic.parentId = parentId;
-      ids.push(topic.id);
-      if (item.children) {
-        const child = getTopicsByAiData(
-          item.children,
-          topic.id,
-          TopicType.sub,
-          topic,
-          graph
-        );
-        topic.children = child.topics;
-        ids.push(...child.ids);
-      }
+      topic.children = child.topics;
+      ids.push(...child.ids);
+    }
 
-      return topic;
-    });
+    return topic;
+  });
 
-    return {
-      topics,
-      ids
-    }
+  return {
+    topics,
+    ids,
   };
+};

+ 0 - 9
apps/flowchart-designer/src/pages/home/index.tsx

@@ -1,9 +0,0 @@
-import React from 'react'
-
-export default function index() {
-  return (
-    <div>
-        页面内容
-    </div>
-  )
-}