Writing in the front

In this paper, an online network topology design and editing based on Jtopo is implemented, which can create complex networks and carry out various operations on networks and devices, providing serialization and anti-sequence operations of topology.

For demonstration purposes, I have deployed a static DEMO to Github, portal

With regard to project access, there are security limitations in reading remote JSON data and opening it directly in a browser. Please put the project into Tomcat for startup access or directly open the project with IDEA /webstorm by right clicking, as shown in the picture below:

The full code is posted separately on Github: github.com/gongxufan/w…

Function introduction

The basic operation can be seen in the GIF below, where a node is dragged from the left icon bar to the edit area. You can drag a line by clicking on the node icon and then releasing the mouse button. Click on the destination node to complete a wire operation. The left column allows you to select a variety of connections.

The layout of the topology editor UI is done by easyUI, and the node editing and wiring is developed based on jTopo. JTopo provides support for stages, scenes, Nodes, containers, and animations. The API is relatively simple to use. The disadvantage is the lack of documentation, but we can get familiar with the DEMO provided by the author. Once familiar with its source code, it is very convenient for secondary development. It’s also easy to use for some animations. Since it’s a Canvas based painting, every change and operation actually redraws the entire canvas. There are still a lot of areas that can be optimized. In fact, d3.js can also go to such an effect, but the recent work is not to explore the back end. Since it is only the front-end part of the personal development project, only this part can be developed due to the company’s permission. If you are interested, you can clone it on my Github for reference. The core part of the code is in editor.js, which provides support for node drag, node wiring, layout and other methods. This is an initial version. Code rough, for reference only. Here are a few important points to explain:

Editor initializes the code

12 3 4 5 6 7 8 9 10 11 12 13 14 15 16Copy the code
// Create JTOP stage screen object
   var canvas = document.getElementById('drawCanvas');  
   canvas.width = $("#contextBody").width();  
   canvas.height = $("#contextBody").height();  
   // Load a blank editor
   if(stageJson == "1") {this.stage = new JTopo.Stage(canvas);  
       this.stage.topoLevel = 1;  
       this.stage.parentLevel = 0;  
       this.modeIdIndex = 1;  
       this.scene=  new JTopo.Scene(this.stage);  
       this.scene.totalLevel = 1;  
   }else{  
       this.stage = JTopo.createStageFromJson(stageJson, canvas);  
       this.scene = this.stage.childs[0];  
   }
Copy the code

We can call jtopo.stage (Canvas) to initialize a drawing area, and then we can use the API to manipulate nodes and animations. The JSON hierarchy of the entire drawing object is as follows:

12 34 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 49Copy the code
{  
  "version": "0.4.8"."deviceNum": "19"."wheelZoom": 0.95."width": 864,  
  "height": 569,  
  "id": "ST172.19.105.52015100809430700001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."childs": [{"elementType": "scene"."id": "S172.19.105.52015100809430700002"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."translateX": 106.5."translateY": 20."scaleX": 1,  
      "scaleY": 1,  
      "totalLevel": "1"."childs": [{"elementType": "node"."id": ""."topoLevel": 1,  
          "parentLevel": "0"."nextLevel": "0"."x": 211.5."y": 135,  
          "width": 32."height": 32."visible": true."rotate": 0."scaleX": 1,  
          "scaleY": 1,  
          "zIndex": 3."deviceId": "1404683827351.4666"."dataType": "VR"."nodeImage": "tpIcon_9.png"."text": "CS Router"."textPosition": "Bottom_Center"."templateId": undefined  
        }  
      ]  
    }  
  ]  
}
Copy the code

Its structure is:

Usually we only need one Scene object to manage all objects, but if we want to achieve more complex grouped object management, we can create multiple Scenes objects to manage separately. At the same time, we can call JTopo. CreateStageFromJson (stageJson, canvas) method to render a save good topology.

Node drag and drop

Node drag-and-drop is implemented using the native H5 drag&drop

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
Copy the code
@param modeDiv * @param drawArea */  
networkTopologyEditor.prototype.drag = function (modeDiv, drawArea, text) {  
    if(! text) text ="";  
    var self = this;  
    // Drag begins, carrying the necessary parameters
    modeDiv.ondragstart = function (e) {  
        e = e || window.event;  
        var dragSrc = this;  
        var backImg = $(dragSrc).find("img").eq(0).attr("src");  
        backImg = backImg.substring(backImg.lastIndexOf('/') + 1);  
        var datatype = $(this).attr("datatype");  
        try {  
            //IE allows only text and URL keys
            e.dataTransfer.setData('text', backImg + ";" + text + ";" + datatype);  
        } catch (ex) {  
            console.log(ex); }};// Block the default event
    drawArea.ondragover = function (e) {  
        e.preventDefault();  
        return false;  
    };  
    // Create a node
    drawArea.ondrop = function (e) {  
        e = e || window.event;  
        var data = e.dataTransfer.getData("text");  
        var img, text,datatype;  
        if (data) {  
            var datas = data.split(";");  
            if (datas && datas.length == 3) {  
                img = datas[0];  
                text = datas[1];  
                datatype = datas[2];  
                var node = new JTopo.Node();  
                node.fontColor = self.config.nodeFontColor;  
                node.setBound((e.layerX ? e.layerX : e.offsetX) - self.scene.translateX - self.config.defaultWidth / 2, (e.layerY ? e.layerY : e.offsetY) - self.scene.translateY - self.config.defaultHeight / 2,self.config.defaultWidth,self.config.defaultHeight);  
                // Device image
                node.setImage(context + 'post/web-topology/icon/' + img);  
                //var cuurId = "device" + (++self.modeIdIndex);  
                var cuurId = "" + new Date().getTime() * Math.random();  
                node.deviceId = cuurId;  
                node.dataType = datatype;  
                node.nodeImage = img;  
                ++self.modeIdIndex;  
                node.text = text;  
                node.layout = self.layout;  
                // Node level
                node.topoLevel = parseInt($("#selectLevel").find("option:selected").val());  
                // The parent level of the node
                node.parentLevel = $("#parentLevel").val();  
                // The layer next to the subnet connection point, which defaults to 0
                node.nextLevel = "0";  
                self.scene.add(node);  
  
                // Load the properties panel
                /* if(self.currDataType) self.clearOldPanels(self.currDataType) self.currDeviceId = cuurId; self.createNewPanels(datatype,self.templateId,self.currentModeId); * /  
                //self.currDataType = datatype;  self.currentNode = node; }}if (e.preventDefault()) {  
            e.preventDefault();  
        }  
        if(e.stopPropagation()) { e.stopPropagation(); }}}Copy the code

The new Node is constructed using jtopo.node (), set its properties, and is added to the Stage via scene.add(Node). Why is the new node visible on the screen when you perform the add operation?

The reason is that the Stage has a frames attribute, which defines the canvas redraw frequency of 1000/frames

Frames properties

Sets the number of frames per second that the current stage plays

The default value is: 24

Frames can be 0, which means that the frames are not drawn automatically, but are triggered manually by the user by calling the paint() method of the Stage object.

If the value is less than 0, the frames will be redrawn only when the keyboard and mouse are active, for example, stage.frames = -24.

The default screen number is 24 frames, which means the screen will be redrawn every 1000/24ms. The background refresh code is as follows:

One, two, three, four, fiveCopy the code
function() {  
             0 == stage.frames ? setTimeout(arguments.callee, 100) : stage.frames < 0 ? (stage.repaint(),  
                        setTimeout(arguments.callee, 1e3 / -stage.frames)) : (stage.repaint(),  
                        setTimeout(arguments.callee, 1e3 / stage.frames))  
        } ()
Copy the code

SetTimeout calls the following redraw function,

12 3 4 5 6 7 8 9 10 11 12 13 14 15Copy the code
this.paint = function() {  
      null! =this.canvas && (this.graphics.save(),  
          this.graphics.clearRect(0.0.this.width, this.height),  
          this.childs.forEach(function(a) {  
                  1 == a.visible && a.repaint(stage.graphics)  
              }  
          ),  
      1= =this.eagleEye.visible && this.eagleEye.paint(this),  
          this.graphics.restore())  
  }  
  ,  
  this.repaint = function() {  
      0! =this.frames && (this.frames < 0 && 0= =this.needRepaint || (this.paint(),  
      this.frames < 0 && (this.needRepaint = !1)))}Copy the code

Paint Calls the repaint method in turn to iterate over all visible objects.

The node connection

The connection method used here is to press the left button of the mouse on the node, and then release the mouse to create a connection. The starting point is the node to be clicked, and the end point will be dynamically updated as the mouse moves. Therefore, if a single node releases the mouse, a line moving with the mouse can be seen. Then click the left button on a node to release how to complete the connection between the two nodes. The effect is as follows:

Part of the code is as follows:

JTopo supports common branches, polylines, curves, and so on, but the corner lengths of polylines can now only be specified at creation time. Second development is required for dynamic second point creation. The code is as follows:

12 3 4 5 6 7 8 9 10 11 12 13 14 15Copy the code
if(self.lineType == "line"){
    self.link = new JTopo.Link(self.tempNodeA, self.tempNodeZ);
    self.link.lineType = "line";
}else if(self.lineType == "foldLine"){
    self.link = new JTopo.FoldLink(self.tempNodeA, self.tempNodeZ);
    self.link.lineType = "foldLine";
    self.link.direction =  self.config.direction;
}else if(self.lineType == "flexLine"){
    self.link = new JTopo.FlexionalLink(self.tempNodeA, self.tempNodeZ);
    self.link.direction =  self.config.direction;
    self.link.lineType = "flexLine";
}else if(self.lineType == "curveLine"){
    self.link = new JTopo.CurveLink(self.tempNodeA, self.tempNodeZ);
    self.link.lineType = "curveLine";
}  xxxxx
Copy the code

Save and load topologies

Because this article is only the front end of the topology editor, the back end part is not open source for commercial reasons. And because the overall project is so large, it will not be easy to separate it. Serialization of topologies is easy as long as we know the load and save logic of topologies. The following takes up a space to focus on the discussion:

Load an existing topology view

We now have a topology, the topology shown by the text portal address, with the following serialization structure:

12 34 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 109 110 111 112 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 166 167 168 169 170 171 172 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 216 217 218 219 220 221 222 223 224 225 226 227 229 230 231 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 285 286 287 288 289 290 291 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 309 310 311 312 313 314 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 378 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 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 645 646 647 648 649Copy the code
{
  "errorInfo": "ok"."topologyJson": {
    "version": "0.4.8"."wheelZoom": "0.95"."deviceNum": "18"."width": "1098"."height": "671"."id": "ST172.19.105.52015100809430700001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."childs": [{"id": "S172.19.105.52015100809430700002"."elementType": "scene"."translateX": "106.5"."translateY": "20"."scaleX": "1"."scaleY": "1"."totalLevel": "1"."parentLevel": "0"."nextLevel": "0"."topoLevel": "1"."childs": [{"id": "L172.19.105.52015100811153300001"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "1136300297928.587"."deviceZ": "1406176935353.6848"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300002"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "1394105924967.951"."deviceZ": "1136300297928.587"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300004"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "564241624829.4331"."deviceZ": "318016674603.1266"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300005"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "1062340763210.1544"."deviceZ": "564241624829.4331"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300006"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "564241624829.4331"."deviceZ": "488323736331.2087"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300007"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "564241624829.4331"."deviceZ": "827722371280.0199"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300008"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "564241624829.4331"."deviceZ": "1045863334277.662"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300009"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "1262070648024.5728"."deviceZ": "564241624829.4331"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811153300010"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "1262070648024.5728"."deviceZ": "1136300297928.587"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811214600001"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "253209434749.73596"."deviceZ": "564241624829.4331"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811214600002"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "253209434749.73596"."deviceZ": "1136300297928.587"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811214600003"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "520008948580.8119"."deviceZ": "564241624829.4331"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811214600004"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "520008948580.8119"."deviceZ": "1136300297928.587"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811512000002"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "809054608657.865"."deviceZ": "1394105924967.951"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100811512000004"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "1250687739831.9912"."deviceZ": "1062340763210.1544"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "L172.19.105.52015100911051100001"."elementType": "link"."x": "0"."y": "0"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "undefined"."deviceA": "564241624829.4331"."deviceZ": "597645745716.1871"."lineType": "line"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "2"
          },
          {
            "id": "N172.19.105.52015100809464700002"."elementType": "node"."x": "198"."y": "315"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "attack-network"."textPosition": "Bottom_Center"."deviceId": "1136300297928.587"."dataType": "EC"."nodeImage": "tpIcon_5.png"."templateId": "NK172.19.105.52015100809464700001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100809465000001"."elementType": "node"."x": "196"."y": "242"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "attackr-router"."textPosition": "Bottom_Center"."deviceId": "1394105924967.951"."dataType": "VR"."nodeImage": "tpIcon_9.png"."templateId": "RT172.19.105.52015100811241800001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100809500700002"."elementType": "node"."x": "104"."y": "383.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "attack-client"."textPosition": "Bottom_Center"."deviceId": "1406176935353.6848"."dataType": "VM"."nodeImage": "tpIcon_2.png"."templateId": "VT172.19.105.52015100910413200001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100810295700002"."elementType": "node"."x": "539"."y": "321.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "intert-networker"."textPosition": "Bottom_Center"."deviceId": "564241624829.4331"."dataType": "EC"."nodeImage": "tpIcon_5.png"."templateId": "NK172.19.105.52015100810295700001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100810320100002"."elementType": "node"."x": "719"."y": "160.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "ws-manage"."textPosition": "Bottom_Center"."deviceId": "318016674603.1266"."dataType": "VM"."nodeImage": "mypc.png"."templateId": "VT172.19.105.52015100810320100001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100810402700002"."elementType": "node"."x": "725"."y": "225.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "ws-browser"."textPosition": "Bottom_Center"."deviceId": "488323736331.2087"."dataType": "VM"."nodeImage": "tpIcon_2.png"."templateId": "VT172.19.105.52015100810402700001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100810461200002"."elementType": "node"."x": "726"."y": "293.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "internal-mssql"."textPosition": "Bottom_Center"."deviceId": "827722371280.0199"."dataType": "VM"."nodeImage": "tpIcon_6.png"."templateId": "VT172.19.105.52015100810461200001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100810485100002"."elementType": "node"."x": "726"."y": "361.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "internal-ossec"."textPosition": "Bottom_Center"."deviceId": "1045863334277.662"."dataType": "VM"."nodeImage": "tpIcon_6.png"."templateId": "VT172.19.105.52015100810485100001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100810523500002"."elementType": "node"."x": "369"."y": "245.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "internet-www"."textPosition": "Bottom_Center"."deviceId": "1262070648024.5728"."dataType": "ECVR"."nodeImage": "vr-selfdefined.png"."templateId": "RT172.19.105.52015100810523500001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100811153300003"."elementType": "node"."x": "536"."y": "237.5"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "intert-router"."textPosition": "Bottom_Center"."deviceId": "1062340763210.1544"."dataType": "VR"."nodeImage": "tpIcon_9.png"."templateId": "RT172.19.105.52015100811281200001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100811163200002"."elementType": "node"."x": "367.5"."y": "320"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "internet-blog"."textPosition": "Bottom_Center"."deviceId": "253209434749.73596"."dataType": "ECVR"."nodeImage": "vr-selfdefined.png"."templateId": "RT172.19.105.52015100811163200001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100811204100002"."elementType": "node"."x": "370.5"."y": "403"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "internet-vpn"."textPosition": "Bottom_Center"."deviceId": "520008948580.8119"."dataType": "ECVR"."nodeImage": "vr-selfdefined.png"."templateId": "RT172.19.105.52015100811204100001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100811512000001"."elementType": "node"."x": "194.5"."y": "166"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "attack-firewall"."textPosition": "Bottom_Center"."deviceId": "809054608657.865"."dataType": "FW"."nodeImage": "tpIcon_4.png"."templateId": "undefined"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100811512000003"."elementType": "node"."x": "534.5"."y": "163"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "intert-firewall"."textPosition": "Bottom_Center"."deviceId": "1250687739831.9912"."dataType": "FW"."nodeImage": "tpIcon_4.png"."templateId": "undefined"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"
          },
          {
            "id": "N172.19.105.52015100911045400002"."elementType": "node"."x": "727.5"."y": "430"."width": "32"."height": "32"."rotate": "0"."scaleX": "1"."scaleY": "1"."text": "defend-client"."textPosition": "Bottom_Center"."deviceId": "597645745716.1871"."dataType": "VM"."nodeImage": "tpIcon_2.png"."templateId": "VT172.19.105.52015100911045400001"."topoLevel": "1"."parentLevel": "0"."nextLevel": "0"."zindex": "3"}]}}Copy the code

We just call on the page

Editor. LoadTopology (” images/backimg. PNG “, “${templateId} ‘, ‘${topologyId}’,” “);

TemplateIdtemplateId and topologyId are the primary key ids involved in the back-end table, which you can ignore here. The loadTopology method code is as follows:

12 34 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, 48Copy the code
JSON data structure * @param backImg Background image of the topology * @param templateId ID of the environment template * @param topologyId Record ID of the topology table */ propertyPanel.prototype.loadTopology =function (backImg,templateId,topologyId,topoLevel) {
    if(! topoLevel) topoLevel ="";
    var self = this;
    self.showLoadingWindow();
    if(! templateId) { templateId = editor.templateId; } $.ajax({ url:'./topology.html',
        async: false.type: "GET",
        dataType: "html",
        data: {
            "templateId":templateId,
            "topologyId":topologyId,
            "topoLevel":topoLevel
        },
        error: function () {
            self.closeLoadingWindow();
            jAlert("Server exception, please try again later..");
        },
        success: function(response) { response = JSON.parse(response); var err = response.errorInfo; // Error handlingif(err && err ! ="ok") {
                if(err == "1"){
                    editor.init(backImg, templateId, topologyId,"1"."");
                }else if (err == "logout") {
                    handleSessionTimeOut();
                    return;
                } else{ self.closeLoadingWindow(); jAlert(err); }}else {
                var topologyJson = response.topologyJson;
                editor.init(backImg, templateId, topologyId, topologyJson,""); }}}); };Copy the code

The logic for topology loading is really implemented in the editor.init method by first sending the request for the JSON data and then processing the response structure. If the requested topology does not exist, create a blank topology. Here is the implementation logic for init:

12 34 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 69Copy the code
/** * the editor initialization method loads a blank or specified topology editor based on the result returned by the request. * @param backImg background image * @param templateId environment templateId * @param topologyId topology record ID * @ param * / networkTopologyEditor JSON stageJson topology structure. The prototype. The init =function (backImg,templateId,topologyId,stageJson,templateName) {
    if(! stageJson){ jAlert("Failed to load topology editor!");
        return; } this.templateId = templateId; this.topologyId = topologyId; // Create JTOP stage screen object var canvas = document.getelementById ('drawCanvas');
    canvas.width = $("#contextBody").width();
    canvas.height = $("#contextBody").height(); // Load a blank editorif(stageJson == "1"){
        this.stage = new JTopo.Stage(canvas);
        this.stage.topoLevel = 1;
        this.stage.parentLevel = 0;
        this.modeIdIndex = 1;
        this.scene=  new JTopo.Scene(this.stage);
        this.scene.totalLevel = 1;
    }else{
        this.stage = JTopo.createStageFromJson(stageJson, canvas);
        this.scene = this.stage.childs[0];
    }
    $("#parentLevel").val(this.stage.parentLevel); // Topology layer switching var options ="";
    for(var i = 1; i <= this.scene.totalLevel ; i++){ options +='<option value="' + i +'"';
        if( i == this.stage.topoLevel){
            options += 'selected="selected" ';
        }
        options += '> edit first ' + i + 'layer < option >';
    }
    $("#selectLevel").append(options); // Zoom this.stage.frames = this.config.stageFrames; this.stage.wheelZoom = this.config.defaultScal; this.stage.eagleEye.visible = this.config.eagleEyeVsibleDefault; this.scene.mode ="edit"; //this.scene. Background = backImg; This. tempNodeA = new jtopo.node ('tempA');
    this.tempNodeA.setSize(1, 1);
    this.tempNodeZ = new JTopo.Node('tempZ'); this.tempNodeZ.setSize(1, 1); this.beginNode = null; this.link = null; var self = this; // Initialize the menu this.initmenus (); // The event handling logic is omitted here... // Enter the topology editor for the first time and generate stage and scene objectsif(stageJson == "1"){
        this.saveToplogy(false); } // Close the loading window this.closeloadingWindow (); }Copy the code

The seemingly complex code here does two things: 1) build the basic stage and scene 2) call JTopo. CreateStageFromJson (stageJson, Canvas) can create the structure of the entire topology 3) initialize and edit its menu 4) finally bind the processing logic of various events 5) Finally create a blank topology if errors occur when obtaining topology data

1
2
3
4
Copy the code
// Enter the topology editor for the first time and generate stage and scene objectsif(stageJson == "1"){
       this.saveToplogy(false);
   }
Copy the code

This completes the task of loading the topology and creating a blank topology

Save the topology view

Saving topologies means serializing the edited topologies into JSON and uploading them to the server to save the database. In the simplest way, we need to follow Node,Scene,Stage. So we define the following entity objects:

Node

12 34 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 52Copy the code
package com.bjhit.cncert.common.beans.models;

import org.codehaus.jackson.map.annotate.JsonSerialize;

/**
 * Created by gongxufan on 2014/11/20.
 */
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Node
{
    private String id;
    private String elementType;
    private String x;
    private String y;
    private String width;
    private String height;
    private String alpha;
    private String rotate;
    private String scaleX;
    private String scaleY;
    private String strokeColor;
    private String fillColor;
    private String shadowColor;
    private String shadowOffsetX;
    private String shadowOffsetY;
    private String zIndex;
    private String text;
    private String font;
    private String fontColor;
    private String textPosition;
    private String textOffsetX;
    private String textOffsetY;
    private String borderRadius;
    private String deviceId;
    private String dataType;
    private String borderColor;
    private String offsetGap;
    private String childNodes;
    private String nodeImage;
    private String templateId;
    private String deviceA;
    private String deviceZ;
    private String lineType;
    private String direction;
    private String vmInstanceId;
    private String displayName;
    private String vmid;
    private String topoLevel;
    private String parentLevel;
    private String nextLevel;
    //getter/setter
}
Copy the code

Scene

12 3 4 5 6 7 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27Copy the code
package com.bjhit.cncert.common.beans.models; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.util.List; /** * Created by gongxufan on 2014/11/20. */ @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) public class Scene  { private String id; private String elementType; private String background; private String backgroundColor; private String mode; private String translateX; private String translateY; private String alpha; private String scaleX; private String scaleY; private String totalLevel; private String parentLevel; private String nextLevel; private String topoLevel; //getter/setter }Copy the code

Stage

12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25Copy the code
package com.bjhit.cncert.common.beans.models; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.util.List; Object * / * * * the topology editor stage Created by gongxufan on 2014/11/20. * / @ JsonSerialize (include = JsonSerialize. Inclusion. NON_NULL) public  class Stage { private String version; private String frames; private String wheelZoom; private String deviceNum; private String width; private String height; private String id; private String totalLevel; private String topoLevel; private String parentLevel; private String nextLevel; private List<Scene> childs; //getter/setter }Copy the code

Having defined these three structures, we have a contrast at the front and back ends. And then how does the front end serialize? Let’s see how the front end serializes the topology:

12 34 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 109 110 111 112 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137Copy the code
/ * * * hold serialized JSON data to the server, in order to reduce the length of the request parameter, and the replacement string. * / propertyPanel prototype. SaveToplogy =function(showAlert) { editor.mainMenu.hide(); var self = this; this.showLoadingWindow(); / / delete first ruler line editor. Utils. ClearRuleLines (); / / save the container state var containers = editor. The utils. GetContainers ();for(var c=0 ; c < containers.length ; c++){
              var temp = [];
              var nodes = containers[c].childs;
              for(var n =0 ; n < nodes.length ; n++){
                  if(nodes[n] instanceof JTopo.Node){
                      temp.push(nodes[n].deviceId);
                  }
              }
            containers[c].childNodes = temp.join(","); } var selectLevel = $("#selectLevel");
        var levels = selectLevel.find("option:selected");
        editor.stage.topoLevel = parseInt(levels.eq(0).val());
        if(editor.stage.topoLevel == -1) editor.stage.topoLevel = 1;
        editor.stage.parentLevel = $("#parentLevel").val();
        editor.scene.totalLevel = selectLevel.find("option").size() - 1;
        topologyJSON = editor.stage.toJson();
        if(topologyJSON){
            for(var key inThis.jsoncode){// Character compression topologyJSON = Topologyjson.replace (new RegExp('"'+ key +'"'."gm"),this.jsonCode[key]);
            }
            topologyJSON = topologyJSON.replace(new RegExp('"'."gm"),'; ');
            topologyJSON = topologyJSON.replace(new RegExp('"'."gm"),The '@');
            topologyJSON = topologyJSON.replace(new RegExp('undefined'."gm"),The '#');
        }
        $.ajax({
            url: context + "topologyManage/saveTopologyJSON",
            async: true.type: "POST",
            dataType: "json",
            data: {
                "topologyJSON": topologyJSON,
                "templateId": editor.templateId,
                "topologyId":editor.topologyId
            },
            error: function () {
                self.closeLoadingWindow();
                jAlert("Server exception, please try again later..");
            },
            success: function(response) { var err = response.errorInfo; // Error handlingif(err && err ! ="ok") {
                    if (err == "logout") {
                        handleSessionTimeOut();
                        return;
                    } else{ self.closeLoadingWindow(); jAlert(err); }}else{* * * s/save the serialized JSON data to the server, in order to reduce the length of the request parameter, and the replacement string. * / propertyPanel prototype. SaveToplogy =function(showAlert) { editor.mainMenu.hide(); var self = this; this.showLoadingWindow(); / / delete first ruler line editor. Utils. ClearRuleLines (); / / save the container state var containers = editor. The utils. GetContainers ();for(var c=0 ; c < containers.length ; c++){
              var temp = [];
              var nodes = containers[c].childs;
              for(var n =0 ; n < nodes.length ; n++){
                  if(nodes[n] instanceof JTopo.Node){
                      temp.push(nodes[n].deviceId);
                  }
              }
            containers[c].childNodes = temp.join(","); } var selectLevel = $("#selectLevel");
        var levels = selectLevel.find("option:selected");
        editor.stage.topoLevel = parseInt(levels.eq(0).val());
        if(editor.stage.topoLevel == -1) editor.stage.topoLevel = 1;
        editor.stage.parentLevel = $("#parentLevel").val();
        editor.scene.totalLevel = selectLevel.find("option").size() - 1;
        topologyJSON = editor.stage.toJson();
        if(topologyJSON){
            for(var key inThis.jsoncode){// Character compression topologyJSON = Topologyjson.replace (new RegExp('"'+ key +'"'."gm"),this.jsonCode[key]);
            }
            topologyJSON = topologyJSON.replace(new RegExp('"'."gm"),'; ');
            topologyJSON = topologyJSON.replace(new RegExp('"'."gm"),The '@');
            topologyJSON = topologyJSON.replace(new RegExp('undefined'."gm"),The '#');
        }
        $.ajax({
            url: context + "topologyManage/saveTopologyJSON",
            async: true.type: "POST",
            dataType: "json",
            data: {
                "topologyJSON": topologyJSON,
                "templateId": editor.templateId,
                "topologyId":editor.topologyId
            },
            error: function () {
                self.closeLoadingWindow();
                jAlert("Server exception, please try again later..");
            },
            success: function(response) { var err = response.errorInfo; // Error handlingif(err && err ! ="ok") {
                    if (err == "logout") {
                        handleSessionTimeOut();
                        return;
                    } else{ self.closeLoadingWindow(); jAlert(err); }}else{ self.replaceStage(editor.templateId,editor.topologyId,showAlert,editor.stage.topoLevel); self.closeLoadingWindow(); }}}); }; self.replaceStage(editor.templateId,editor.topologyId,showAlert,editor.stage.topoLevel); self.closeLoadingWindow(); }}}); };Copy the code
  1. To delete the ruler line (edit the horizontal and vertical lines displayed in the area), this object needs to be removed from our structure by calling the clearRuleLines method.
  2. The node objects of the containers area need to be extracted, because these nodes are already included when the call is serialized, so only their node IDS need to be associated with the container when it is loaded into the library
  3. If hierarchical editing is supported, the number of layers in the current topology is also saved
  4. A call to editor.stage.tojson () gets the structure of the entire topology
  5. Json substitution, just to reduce data transfer
  6. Finally, the parsed JSON is sent to the background processing

Other details will not be described here. This project requires readers to have basic knowledge of H5, easyUI, jTopo, Canvas, JSON and so on. As for jTopo, just look at the DEMO and few apis provided by the author and you can get started very quickly. The best way to learn is to break the debug trace at different points and see how the whole thing works. The topology editing shown here is also a very simple and incomplete example, but there are many things that can be customized, such as the wiring and the way the wiring is done, which can be further customized.

end

Resources: www.jtopo.com/

www.jeasyui.com/documentati…

www.w3school.com.cn/html5/