mind map 思维导图

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Mind Map</title>
    <meta name="description"
        content="A mind map editor, showing how subtrees can be moved, copied, deleted, and laid out." />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Copyright 1998-2019 by Northwoods Software Corporation. -->

    <script src="https://unpkg.com/gojs/release/go-debug.js"></script>
    <script id="code">
        function init() {
            if (window.goSamples) goSamples(); // 这些样本的初始化-您无需调用此
            var $ = go.GraphObject.make;

            myDiagram =
                $(go.Diagram, "myDiagramDiv", {
                    "maxSelectionCount": 1, // 用户一次只能选择一个节点
                    "initialContentAlignment": go.Spot.Center, // 画布内居中显示
                    "allowZoom": true, //画布是否可以缩放
                    // 当用户拖动节点时,还要从该节点开始移动/复制/删除整个子树
                    "commandHandler.copiesTree": true,
                    "commandHandler.copiesParentKey": true,
                    "commandHandler.deletesTree": true,
                    "draggingTool.dragsTree": true, //拖拽?
                    "undoManager.isEnabled": false, //  支持 Ctrl-Z 和 Ctrl-Y 操作
                    //禁止横竖拖动和鼠标滚动,流程图整体的拖动
                    "allowHorizontalScroll": false,
                    "allowVerticalScroll": false,
                    "isReadOnly": true, // 只读
                });

            // 当文档被修改时,在标题中添加“*”并启用“Save”按钮
            myDiagram.addDiagramListener("Modified", function (e) {
                var button = document.getElementById("SaveButton");
                if (button) button.disabled = !myDiagram.isModified;
                var idx = document.title.indexOf("*");
                if (myDiagram.isModified) {
                    if (idx < 0) document.title += "*";
                } else {
                    if (idx >= 0) document.title = document.title.substr(0, idx);
                }
            });

            // 一个节点由一些文本和一条线形状组成
            myDiagram.nodeTemplate =
                $(go.Node, "Vertical", {
                        selectionObjectName: "TEXT",
                        click: function (e, obj) {
                            myDiagram.selected = true;
                        },
                        // 选择节点变化监听
                        selectionChanged: function (part) {
                            myDiagram.selected = false;;
                        }

                    },
                    $(go.TextBlock, {
                            name: "TEXT",
                            minSize: new go.Size(30, 15),
                            editable: false //是否允许双击编辑
                        },
                        // 不仅要记住文本字符串,还要记住节点数据中的比例和字体
                        new go.Binding("text", "text").makeTwoWay(),
                        new go.Binding("scale", "scale").makeTwoWay(),
                        new go.Binding("font", "font").makeTwoWay()),
                    $(go.Shape, "LineH", {
                            stretch: go.GraphObject.Horizontal,
                            strokeWidth: 3,
                            height: 3,
                            // 这条线的形状是端口——连接的是什么
                            portId: "",
                            fromSpot: go.Spot.LeftRightSides,
                            toSpot: go.Spot.LeftRightSides
                        },
                        new go.Binding("stroke", "brush"),
                        // 确保链接来自正确的方向,并适当地发送出去
                        new go.Binding("fromSpot", "dir", function (d) {
                            return spotConverter(d, true);
                        }),
                        new go.Binding("toSpot", "dir", function (d) {
                            return spotConverter(d, false);
                        })),
                    // 记住节点数据中每个节点的位置
                    new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
                    // 确保文本按照期望的方向“增长”
                    new go.Binding("locationSpot", "dir", function (d) {
                        return spotConverter(d, false);
                    })
                );

            // 选中的节点显示用于添加子节点的按钮
            myDiagram.nodeTemplate.selectionAdornmentTemplate =
                $(go.Adornment, "Spot",
                    $(go.Panel, "Auto",
                        // 此装饰在选定节点周围具有矩形蓝色形状
                        $(go.Shape, {
                            fill: null,
                            stroke: "dodgerblue",
                            strokeWidth: 3
                        }),
                        $(go.Placeholder, {
                            margin: new go.Margin(4, 15, 0, 4)
                        })
                    ),
                    // 所选节点右侧的删除按钮
                    $("Button", {
                            alignment: go.Spot.Right,
                            alignmentFocus: go.Spot.Left,
                            click: function (e, obj) {
                                e.diagram.commandHandler.deleteSelection();
                                layoutAll(); // 删除后整理布局
                            }
                            // 定义装饰中此按钮的单击行为
                        },
                        $(go.TextBlock, "-", // 按钮的内容
                            {
                                font: "bold 8pt sans-serif"
                            })
                    ),
                    // 所选节点右侧的新增按钮
                    $("Button", {
                            alignment: go.Spot.Right,
                            alignmentFocus: go.Spot.Right,
                            click: addNodeAndLink // 定义装饰中此按钮的单击行为
                        },
                        $(go.TextBlock, "+", // 按钮的内容
                            {
                                font: "bold 8pt sans-serif"
                            })
                    )
                );

            // 上下文菜单允许用户更改字体大小和粗细,
            // 并从该节点开始执行有限的树形布局
            myDiagram.nodeTemplate.contextMenu =
                $("ContextMenu",
                    $("ContextMenuButton",
                        $(go.TextBlock, "Bigger"), {
                            click: function (e, obj) {
                                changeTextSize(obj, 1.1);
                                layoutAll();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Smaller"), {
                            click: function (e, obj) {
                                changeTextSize(obj, 1 / 1.1);
                                layoutAll();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Bold/Normal"), {
                            click: function (e, obj) {
                                toggleTextWeight(obj);
                                layoutAll();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Copy"), {
                            click: function (e, obj) {
                                e.diagram.commandHandler.copySelection();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Delete"), {
                            click: function (e, obj) {
                                e.diagram.commandHandler.deleteSelection();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Undo"), {
                            click: function (e, obj) {
                                e.diagram.commandHandler.undo();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Redo"), {
                            click: function (e, obj) {
                                e.diagram.commandHandler.redo();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Layout"), {
                            click: function (e, obj) {
                                var adorn = obj.part;
                                adorn.diagram.startTransaction("Subtree Layout");
                                layoutTree(adorn.adornedPart);
                                adorn.diagram.commitTransaction("Subtree Layout");
                            }
                        }
                    )
                );

            // 连接线颜色
            myDiagram.linkTemplate =
                $(go.Link, {
                        curve: go.Link.Bezier,
                        fromShortLength: -2,
                        toShortLength: -2,
                        selectable: false
                    },
                    $(go.Shape, {
                            strokeWidth: 3
                        },
                        new go.Binding("stroke", "toNode", function (n) {
                            if (n.data.brush) return n.data.brush;
                            return "black";
                        }).ofObject())
                );

            // 该图的上下文菜单仅显示常规功能的命令
            myDiagram.contextMenu =
                $("ContextMenu",
                    $("ContextMenuButton",
                        $(go.TextBlock, "Paste"), {
                            click: function (e, obj) {
                                e.diagram.commandHandler.pasteSelection(e.diagram.toolManager.contextMenuTool
                                    .mouseDownPoint);
                            }
                        },
                        new go.Binding("visible", "", function (o) {
                            return o.diagram && o.diagram.commandHandler.canPasteSelection(o.diagram.toolManager
                                .contextMenuTool.mouseDownPoint);
                        }).ofObject()),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Undo"), {
                            click: function (e, obj) {
                                e.diagram.commandHandler.undo();
                            }
                        },
                        new go.Binding("visible", "", function (o) {
                            return o.diagram && o.diagram.commandHandler.canUndo();
                        }).ofObject()),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Redo"), {
                            click: function (e, obj) {
                                e.diagram.commandHandler.redo();
                            }
                        },
                        new go.Binding("visible", "", function (o) {
                            return o.diagram && o.diagram.commandHandler.canRedo();
                        }).ofObject()),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Save"), {
                            click: function (e, obj) {
                                save();
                            }
                        }),
                    $("ContextMenuButton",
                        $(go.TextBlock, "Load"), {
                            click: function (e, obj) {
                                load();
                            }
                        })
                );

            myDiagram.addDiagramListener("SelectionMoved", function (e) {
                var rootX = myDiagram.findNodeForKey(0).location.x;
                myDiagram.selection.each(function (node) {
                    if (node.data.parent !== 0) return; // 只考虑连接到根的节点
                    var nodeX = node.location.x;
                    if (rootX < nodeX && node.data.dir !== "right") {
                        updateNodeDirection(node, "right");
                    } else if (rootX > nodeX && node.data.dir !== "left") {
                        updateNodeDirection(node, "left");
                    }
                    layoutTree(node);
                });
            });

            //监听节点选择变化
            //myDiagram.addDiagramListener("ChangedSelection", function (e) {
            //myDiagram.selected = false;
            //});

            //监听单击
            myDiagram.addDiagramListener("ObjectSingleClicked", function (e) {
                //如果是选中后单击
                if (myDiagram.selected) {
                    console.log('选中后单击,表示编辑,需打开浮窗编辑');
                }
            });

            //背景点击一次
            myDiagram.addDiagramListener("BackgroundSingleClicked", function (e) {
                console.log("点击背景");
                //$scope.nodeFocusOutInner();
            });

            // 使用“ mySavedModel”文本区域中保存的JSON格式数据读取预定义的图形
            load();
        }

        function spotConverter(dir, from) {
            if (dir === "left") {
                return (from ? go.Spot.Left : go.Spot.Right);
            } else {
                return (from ? go.Spot.Right : go.Spot.Left);
            }
        }

        function changeTextSize(obj, factor) {
            var adorn = obj.part;
            adorn.diagram.startTransaction("Change Text Size");
            var node = adorn.adornedPart;
            var tb = node.findObject("TEXT");
            tb.scale *= factor;
            adorn.diagram.commitTransaction("Change Text Size");
        }

        function toggleTextWeight(obj) {
            var adorn = obj.part;
            adorn.diagram.startTransaction("Change Text Weight");
            var node = adorn.adornedPart;
            var tb = node.findObject("TEXT");
            // 假定“粗体”在字体说明符的开头
            var idx = tb.font.indexOf("bold");
            if (idx < 0) {
                tb.font = "bold " + tb.font;
            } else {
                tb.font = tb.font.substr(idx + 5);
            }
            adorn.diagram.commitTransaction("Change Text Weight");
        }

        function updateNodeDirection(node, dir) {
            myDiagram.model.setDataProperty(node.data, "dir", dir);
            // 递归更新子节点的方向
            var chl = node
                .findTreeChildrenNodes(); // 为我们提供了与此特定节点相关的子节点的迭代器
            while (chl.next()) {
                updateNodeDirection(chl.value, dir);
            }
        }

        function addNodeAndLink(e, obj) {
            var adorn = obj.part;
            var diagram = adorn.diagram;
            diagram.startTransaction("Add Node");
            var oldnode = adorn.adornedPart;
            var olddata = oldnode.data;
            // 将笔刷和方向复制到新的节点数据
            var newdata = {
                text: "idea",
                 olddata.brush,
                dir: olddata.dir,
                parent: olddata.key
            };
            diagram.model.addNodeData(newdata);
            layoutTree(oldnode);
            diagram.commitTransaction("Add Node");

            // 如果新节点不在屏幕上,请滚动图表以显示新节点
            var newnode = diagram.findNodeForData(newdata);
            if (newnode !== null) diagram.scrollToRect(newnode.actualBounds);
            layoutAll(); //添加完毕 整理布局
        }

        function layoutTree(node) {
            if (node.data.key === 0) { // 添加到根?
                layoutAll(); // 整理布局
            } else { // 否则,仅布局从此父节点开始的子树
                var parts = node.findTreeParts();
                layoutAngle(parts, node.data.dir === "left" ? 180 : 0);
            }
        }

        function layoutAngle(parts, angle) {
            var layout = go.GraphObject.make(go.TreeLayout, {
                angle: angle,
                arrangement: go.TreeLayout.ArrangementFixedRoots,
                nodeSpacing: 5,
                layerSpacing: 20,
                setsPortSpot: false, // 不要设置端口点,因为我们正在使用spotConverter函数进行管理
                setsChildPortSpot: false
            });
            layout.doLayout(parts);
        }

        function layoutAll() {
            var root = myDiagram.findNodeForKey(0);
            if (root === null) return;
            myDiagram.startTransaction("Layout");
            // 将节点和链接分为两个集合
            var rightward = new go.Set( /*go.Part*/ );
            var leftward = new go.Set( /*go.Part*/ );
            root.findLinksConnected().each(function (link) {
                var child = link.toNode;
                if (child.data.dir === "left") {
                    leftward.add(root); // 根节点在两个集合中
                    leftward.add(link);
                    leftward.addAll(child.findTreeParts());
                } else {
                    rightward.add(root); // 根节点在两个集合中
                    rightward.add(link);
                    rightward.addAll(child.findTreeParts());
                }
            });
            // 进行一个布局,然后进行另一个布局而不移动共享的根节点
            layoutAngle(rightward, 0);
            layoutAngle(leftward, 180);
            myDiagram.commitTransaction("Layout");
        }

        // 以JSON格式显示图的模型
        function save() {
            document.getElementById("mySavedModel").value = myDiagram.model.toJson();
            myDiagram.isModified = false;
        }

        function load() {
            var data = {
                "class": "TreeModel",
                "nodeDataArray": []
            };
            //myDiagram.model = go.Model.fromJson(data);
            myDiagram.model = go.Model.fromJson(document.getElementById("mySavedModel").value);
        }
    </script>
</head>

<body onload="init()">
    <div id="sample">
        <div id="myDiagramDiv" style="border: solid 1px black; 100%; height:300px;"></div>
        <p>
            A mind map is a kind of spider diagram that organizes information around a central concept, with connecting
            branches.
        </p>
        <p>
            The layout is controlled by moving the nodes closest to the tree's root node.
            When one of these nodes is moved horizontally to the other side of the root,
            all of its children will be sent to <a>Layout.doLayout</a> with a new direction,
            causing text to always be moved outwards from the root. The <b>spotConverter</b> function is used to manage
            <a>GraphObject.fromSpot</a> and <a>GraphObject.toSpot</a> for nodes manually, so the
            <a>TreeLayout.setsPortSpot</a> and <a>TreeLayout.setsChildPortSpot</a>
            properties are set to false so that laying out the diagram will not overwrite the values.
        </p>
        <p>
            When a node is deleted the <a>CommandHandler.deletesTree</a> property ensures that
            all of its children are deleted with it. When a node is dragged the <a>DraggingTool.dragsTree</a>
            property ensures that all its children are dragged with it.
            Both of these are set during the the Diagram's initalization.
        </p>
        <p>
            Node templates also have a <a>Part.selectionAdornmentTemplate</a> defined to allow for new nodes to be
            created and a <a>GraphObject.contextMenu</a> with additional commands.
        </p>

        <button id="SaveButton" onclick="save()">Save</button>
        <button onclick="load()">Load</button>
        <button onclick="layoutAll()">Layout</button>
        Diagram Model saved in JSON format:
        <br />
        <textarea id="mySavedModel" style="100%;height:400px">
{ "class": "TreeModel",
  "nodeDataArray": [ 
{"key":0, "text":"Mind Map", "loc":"-400 9"},
{"key":1, "parent":0, "text":"Getting more time", "brush":"skyblue", "dir":"right", "loc":"-315.47607421875 -14.134118652343766"},
{"key":11, "parent":1, "text":"Wake up early", "brush":"skyblue", "dir":"right", "loc":"-180.62158203125 -41.64627685546877"},
{"key":12, "parent":1, "text":"Delegate", "brush":"skyblue", "dir":"right", "loc":"-180.62158203125 -14.13411865234377"},
{"key":13, "parent":1, "text":"Simplify", "brush":"skyblue", "dir":"right", "loc":"-180.62158203125 13.378039550781233"},
{"key":2, "parent":0, "text":"More effective use", "brush":"darkseagreen", "dir":"right", "loc":"-315.47607421875 54.64627685546874"},
{"key":21, "parent":2, "text":"Planning", "brush":"darkseagreen", "dir":"right", "loc":"-180.28515625 40.890197753906236"},
{"key":211, "parent":21, "text":"Priorities", "brush":"darkseagreen", "dir":"right", "loc":"-105.87939453125 27.134118652343737"},
{"key":212, "parent":21, "text":"Ways to focus", "brush":"darkseagreen", "dir":"right", "loc":"-105.87939453125 54.646276855468734"},
{"key":22, "parent":2, "text":"Goals", "brush":"darkseagreen", "dir":"right", "loc":"-180.28515625 68.40235595703125"}
 ]}
  </textarea>
    </div>
</body>

</html>
原文地址:https://www.cnblogs.com/Alwaysbecoding/p/11865751.html