JavaScript Flow Chart And Workflow With C# ASP.NET MVC

Introduction

As soon as we wake in the morning, we start to make decisions - do we stay in bed? (weekend, yea!), or get out of the bed? (get to work, must catch the train...). Once we make that first decision, we might take an action (grab a coffee!), or ponder another decision (do I need to visit the bathroom first?). As the day progresses, our life is one decision after another. Its the same in every organization. In one way, we can say that life, and how it goes, is based on infinite possibilities of flow-states :)

This article is about a very useful Javascript library called 'JS plumb', and how it can help us build flow-chart or work-flow style capabilities into our .net web based applications. As you might expect these days, its not restricted to .net, and not restricted to MVC, but for this article, that's what I've chosen to focus on.



Background

I have frequently come across situations where I wish to give the user the some form of decision making in how a program executes. This may be based on a simple series of hard-coded states (yes/no, if X then choose from a list of Y actions), or may be more complex with an underlying automation system such as that provided by Windows workflow foundation. I always loved the visual aspect of workflow foundation, and missed the ability to be able to provide that wonderful drag and drop work-flow-builder experience we have in visual studio to the end user.


When I came across JSPlumb, I was immediately excited by the possibilities. It's a very flexible library that manages objects on a canvas and the connections between them - its focus is on providing a solution for the 'plumbing' part of a flow-chart or work-flow style user interface. As with a lot of these libraries, there is an open source community edition, and one that's more advanced. The latter is known as JSPlumb Toolkit and comes with commercial support. JSPlumb uses SVG and runs on all browsers from IE9 and up.

The basics

Before we start jumping into code, let's have a look at the basics of how things hang together visually with flow-charts, and JSPlumb in particular.



There are a lot of common things you will be aware of in the above diagram,

  • a workfow or flow-chart usually has some kind of starting point
  • there are lines that connect things together
  • we have shapes that represent decisions that have to be made, and actions to be taken
  • the direction of the connection between shapes is usually represented by arrows, and annotated with text of some kind.

If we zoom in on that picture a little bit closer, JSPlumb defines things as follows,



The visual objects are split into two groups. There are the objects of interest which are called the 'source' and 'target', and then the things that connect these objects. Each source or target can have 0:M anchor positions. The anchors are points on the object that the connectors can hook onto. Connectors allow objects to be linked together. Connectors link to an end-point at an anchor at either end on the source or target - as they are bidirectional, there is no start or end 'end-point', simply, endpoints! 

Getting started

The first thing to understand about the library is that it works using a series of DIV objects that you define. Unlike other JS libraries that get you to define a DIV as a boundary and use this as a canvas to draw on, JSPlumb simply says - "tell me what DIVs are your flow-chart shapes, and I will connect them". This makes sense, given the name of the library - its not flowchartJS or WorkFlowJS, its about joining things together, its literally the 'plumbing' !

To demonstrate this, let's define two DIVs, and then join them together with JSPlumb. First, the divs...

  1. <div class="shape" id="shape1"></div>  
  2. <div class="shape" id="shape2"></div>  

and some styling

  1.   .shape {  
  2.   float:left;  
  3.   margin:10px;  
  4.   width: 100px;  
  5.   height: 100px;  
  6.   border: solid 1px;  
  7. }  

And now, the magic....

  1. jsPlumb.ready(function() {  
  2.     jsPlumb.connect({  
  3.         source:"shape1",  
  4.         target:"shape2"  
  5.     });  
  6. });  

In the same way we can direct Javascript to trigger when the DOM is ready, in this case we tell jsPlumb to execute the 'connect' method for our first two shapes onces its loaded and ready to go. Heres how it looks once rendered ... all smiley-face like!



We didn't have to define the position for the connection or the anchor or endpoint shape - it used its own defaults, 'bottom' and 'round'.

Shapes

The building blocks of our flowchart are shapes - we connect them together, but the shape itself usually signifies something. Diamonds or triangles mean decisions, circles convergence points, etc. It all depends on the application (think flow-chart versus entity relationship diagram versus web based work-flow). JSPlumb is not responsible for styling the shapes, thats up to you, and your old friend CSS. Whatever you stlye, JSPlumb will hook up. Here are some examples you may commonly see in a flow-chart application.

NB

You can get some great CSS Shape examples at 
CSS Tricks, for fine tuning of colours you could do worse than refer to HTMLColorCodes.


HTML Declaring the CLASS to style each DIV

  1. <div id="shape1" class="shape square"></div>  
  2. <div id="shape2" class="shape circle"></div>  
  3. <div id="shape3" class="shape triangle-down"></div>  
  4. <div id="shape4" class="shape parallelogram"></div>  

CSS styling for each example

  1. .shape {  
  2.   float:left;  
  3.   margin:80px;  
  4.   width: 100px;  
  5.   height: 100px;  
  6.   border: solid 1px;  
  7. }  
  8.   
  9. .square {  
  10.     width: 100px;  
  11.     height: 100px;  
  12.     background: #76D7C4;  
  13. }  
  14.   
  15. .circle {  
  16.     width: 100px;  
  17.     height: 100px;  
  18.     background: red;  
  19.     -moz-border-radius: 50px;  
  20.     -webkit-border-radius: 50px;  
  21.     border-radius: 50px;  
  22.   background: #F7DC6F  
  23. }  
  24.   
  25. .triangle-down {  
  26.     width: 0;  
  27.     height: 0;  
  28.     border-left: 50px solid transparent;  
  29.     border-right: 50px solid transparent;  
  30.     border-top: 100px solid red;  
  31. }  
  32.   
  33. .parallelogram {  
  34.     width: 150px;  
  35.     height: 100px;  
  36.     -webkit-transform: skew(20deg);  
  37.        -moz-transform: skew(20deg);  
  38.          -o-transform: skew(20deg);  
  39.     background: blue;  
  40. }  

Let's see what else we can do to tweak the endpoints and connections. First, let's look at the anchors, the points on the shape itself that the connectors hook onto.

Anchors

Changing where the connectors anchor is done by setting the anchors property

  1. jsPlumb.ready(function() {  
  2.     jsPlumb.connect({  
  3.         source:"shape1",  
  4.         target:"shape2",  
  5.         anchor:"Top"  
  6.     });  
  7. });  

Valid options are,

  • Top(also aliased as TopCenter)
  • TopRight
  • Right(also aliased as RightMiddle)
  • BottomRight
  • Bottom(also aliased as BottomCenter)
  • BottomLeft
  • Left(also aliased as LeftMiddle)
  • TopLeft
  • Center

Some examples



In addition to the static anchors listed above, there are other options available to you including Dynamic and Peripheral. The latter are interesting, as they are dynamically created depending on the type of shape you define the object source or target DIV to be. For example, if you have a decision object, you might choose a diamond shape - in this case the library will automatically put the anchors in the most logical position which would be the corners of the diamond. You get similar options using for example the circle/oval - the documentation for jsplumb anchors outlines what you need to know should you need this level of flexibility. 

Endpoints

Endpoints are the intersection of connectors and anchors. They can be styled using some built-in shapes, images or custom CSS.


Different endpoint types you can use are as follows,

  • DotThis Endpoint draws a dot on the screen. It supports three constructor parameters,

    • radius- Optional; defaults to 10 pixels. Defines the radius of the dot.
    • cssClass- Optional. A CSS class to attach to the element the Endpoint creates.
    • hoverClass- Optional. A CSS class to attach to the element the Endpoint creates whenever the mouse is hovering over the element or an attached Connection.

  • RectangleDraws a rectangle. Supported constructor parameters are,

    • widthOptional; defaults to 20 pixels. Defines the width of the rectangle.
    • heightOptional; defaults to 20 pixels. Defines the height of the rectangle.
    • cssClass A CSS class to attach to the element the Endpoint creates.
    • hoverClass A CSS class to attach to the element the Endpoint creates whenever the mouse is hovering over the element or an attached Connection.

  • ImageDraws an image from a given URL. This Endpoint supports three constructor parameters,

    • src Specifies the URL of the image to use
    • cssClass A CSS class to attach to the element the Endpoint creates.
    • hoverClass A CSS class to attach to the element the Endpoint creates whenever the mouse is hovering over the element or an attached Connection.

  • BlankDoes not draw anything visible to the user. This Endpoint is probably not what you want if you need your users to be able to drag existing Connections - for that, use a Rectangle or Dot Endpoint and assign to it a CSS class that causes it to be transparent.

Connectors

The lines that allow us to create the links between shapes are connectors. Like endpoints and anchors, they have different options that we can use. The connector carries with it some of the other concepts,

  • Anchors are the places on the shapes that connectors can hook onto
  • Endpoints are a visual representation of one end of a connection, which are mostly but not always attached visibly to shapes, giving an indication of where connectors can hook onto

JSPlumb has four standard connectors - a bezier curve (this is the default), a straight line, a 'flowchart' mode, and a 'state machine' mode. 

Connectors and their options are generally specified using the connector property when we call any of the following methods

  • connect
  • addEndpoint(s)
  • makeSource
  • makeTarget

Here are some examples of building a connection, and setting the type of connection that is rendered

Example 1 - JSPlumb Connector

Bezier with different curve radius

  1.   jsPlumb.connect({  
  2.   source:"shape1",  
  3.   target:"shape2",  
  4.   connector:[ "Bezier", { curviness:150 } ]  
  5. });  
  6.   
  7.   jsPlumb.connect({  
  8.   source:"shape3",  
  9.   target:"shape4",  
  10.   connector:[ "Bezier", { curviness:50 } ]  
  11. });  

 

Example 2 - JSPlumb Connector

Straight and flowchart connectors with options

  1.   jsPlumb.connect({  
  2.   source:"shape1",  
  3.   target:"shape2",  
  4.   connector:[ "Straight" ],  
  5.   anchors:["Top""Bottom"],  
  6.   endpoint:[ "Rectangle", { width:20, height:40 }]  
  7. });  
  8.   
  9.   jsPlumb.connect({  
  10.   source:"shape3",  
  11.   target:"shape4",  
  12.   connector:[ "Flowchart", {cornerRadius:15}]  
  13. });  
  14.   
  15.   jsPlumb.connect({  
  16.   source:"shape5",  
  17.   target:"shape6",  
  18.   connector:[ "Flowchart", {stub:10, gap:20}]  
  19. });  

The options used above are 'cornerRadius', which puts a curve on the corner of the connector as it connects, 'gap' which introduces a space between the connector and the endpoint, and 'stub' which gives a squared edge to the connection. 

In addition to talking about the connector options, there we have two other concepts we have still to talk about:

  • Overlaysare UI elements that can be used to decorate a connector - for example an arrow indicating direction of the connector, or a text overlay on the connector line itself describing the connection.
  • Groupsallow you to have a collection of elements 'grouped' inside another element, which can be collapsed and expanded - this could be very useful in a work-flow chart to allow the user to drill down into detail on a particular workflow process.

Overlays

The lines that make up the connectors have options available to them as well. Amongst these are overlays. These are elements like display text along the conneciton line and arrowheads. In the following example code we are going to do a few things with the overlay, add some text and style it, and add a number of different arrows.

FIrst, let's see the end result, then we'll look at how its built up



As I want to offload the styling for the 'Sample text' overlay label onto a CSS class, we'll define this first

  1. .labelClass {  
  2.     background-color:yellow;   
  3.     padding:0.4em;   
  4.     font:16px sans-serif;   
  5.     color:#444;  
  6.     z-index:21;  
  7.     border:1px solid red;  
  8. }  

Now let's look at the JSPlumb setup code 

  1. jsPlumb.connect({  
  2. source:"shape1",  
  3. target:"shape2",  
  4. paintStyle: { strokeStyle: "orange", lineWidth: 5 },  
  5. connector:[ "Bezier", { curviness:100 } ],  
  6. overlays:[   
  7.    [ "Arrow", { width:20, length:15, location:[.1], foldback: 1,  
  8.               paintStyle: { strokeStyle: "red", lineWidth: 2 } }   
  9.               ],  
  10.    [ "Arrow", { width:20, length:15, location:[.2],   
  11.               paintStyle: { strokeStyle: "green", lineWidth: 2 } }   
  12.               ],  
  13.    [ "Arrow", { width:20, length:15, location:[.3], direction:-1,  
  14.               paintStyle: { strokeStyle: "blue", lineWidth: 2 } }   
  15.               ],                  
  16.    [ "Arrow", { width:50, length:30, location:[.9] } ],  
  17.    [ "Label", {   
  18.                  label:"Sample text",  
  19.                       location:0.5,  
  20.                       id:"label",  
  21.                       cssClass:"labelClass"  
  22.                   }],  
  23.   ]     
  24. ;  

As before, we start by declaring the source and target shapes.

  1. source:"shape1", target:"shape2"  

Next, we define how we want the main paint style to look

  1. paintStyle: {  
  2.     strokeStyle: "orange",  
  3.     lineWidth: 5  
  4. }  

Our connector is a bezier curve

  1. connector: ["Bezier", {  
  2.     curviness: 100  
  3. }]  

And here come the overlays....

The first one is an arrow. Its location is 10% from the source '.1'. The location works either as a proportional value from 0 to 1 inclusive (so in this case, '.1' = 10%), or as an an absolute value, where negative values mean distance from target, and positive values (greater than 1) mean the distance from source. Foldback refers to the fold at the base of the arrow. Negative numbers cause it to float out, like a diamond shape, positive number make for a skinny pointy arrow. We'll see an example of this shortly.

  1. "Arrow", {  
  2.     width: 20,  
  3.     length: 15,  
  4.     location: [.1],  
  5.     foldback: 1,  
  6.     paintStyle: {  
  7.         strokeStyle: "red",  
  8.         lineWidth: 2  
  9.     }  
  10. }  

The main feature of the next arrow is it uses the default foldback, and we have changed the stroke color,

  1. ["Arrow", {  
  2.         width: 20,  
  3.         length: 15,  
  4.         location: [.2],  
  5.         paintStyle: {  
  6.             strokeStyle: "green",  
  7.             lineWidth: 2  
  8.         }  
  9.     }  

Coming hot on the heels of Mr. Foldback, comes Ms.Reverse! ... here we set the 'Direction' property to be '-1'. The default is '1'.

  1. "Arrow", { width:20, length:15, location:[.3], direction:-1,  
  2.                 paintStyle: { strokeStyle: "blue", lineWidth: 2 } }   
  3.                 ],  

The last arrow of this example is a biggie - we change the dimensions of it by adjusting the width and length.

  1. "Arrow", { width:50, length:30, location:[.9] } ]  

Getting text in is very simple. You will recall that earlier we defined some CSS to style our label - here is where we call it.

  1. "Label", {  
  2.               label:"Sample text",  
  3.                    location:0.5,  
  4.                    id:"label",  
  5.                    cssClass:"labelClass"  
  6.                }]  

The key bits from the above code are the 'label' which feeds the text you wish to display, and the cssClass we wish to use for styling.

Heres a closer look at how the arrows work with another example, you can follow the code underneath to see how each one is designed.

  1.   jsPlumb.connect({  
  2.   source:"shape3",  
  3.   target:"shape4",  
  4.   connector:[ "Straight"],  
  5.   anchors: ["Right""Left"],  
  6.   paintStyle: { strokeStyle: "orange", lineWidth: 1 },  
  7.   overlays:[   
  8.      [ "Arrow", { width:30, length:25, location:[.2], foldback: 1,  
  9.                 paintStyle: { strokeStyle: "red", lineWidth: 2 } }   
  10.                 ],  
  11.      [ "Arrow", { width:20, length:15, location:[.4],   
  12.                 paintStyle: { strokeStyle: "green", lineWidth: 1 } }   
  13.                 ],  
  14.      [ "Arrow", { width:20, length:15, location:[.65],  foldback: 2,  
  15.                 paintStyle: { strokeStyle: "red", lineWidth: 8 } }   
  16.                 ],                  
  17.      [ "Arrow", { width:20, length:15, location:[.8], direction:-1,  
  18.                 paintStyle: { strokeStyle: "blue", lineWidth: 2 } }   
  19.                 ]  
  20.     ]     
  21. });  

Groups

The library has a concept called 'Groups' that works pretty much as you would expect, with an additional bonus. Grouping allows you to take a set of shapes, and group them together within the scope of a parent container. Any connectors from these child shapes to other shapes on your UI are retained. Now there are two cool things to note,

  • when you drag/move the parent/group container shape, all of the child shapes within it move with it.
  • you can collapse and expand the 'parent' group container, and as you do, any connectors that were previously linked visually to other shapes, are 'proxied' up onto the groups collapsed element.

Heres a screenshot that shows grouping,



Ref: documentation page about grouping in JSPlumb.

Common options

A lot of the time you may find you are repeating yourself with setting endpoint styles, connectors, etc. It may also be the case that in a complex applicaiton you want to have one set of styles for one type of element, and another set for the next. To help with this, we can pass in a plain old Javascript object as a 'common option' into Endpoint, Connector, Anchor and Overlay methods. 

  1. var commonEndpoint = {  
  2.       stub:"90",  
  3.       gap:"15"  
  4. };  
  5.     
  6.   jsPlumb.connect({  
  7.   source:"shape5",  
  8.   target:"shape6",  
  9.   connector:[ "Flowchart", commonEndpoint]  
  10. });  

Drag and drop

Another useful, and I think critical feature of a good flowchart/diagram utility is the ability to drag and drop elements onto the canvas. Drag/drop is initiated by introducing the 'draggable' method to an element:

  1. <code data-lang="javascript">jsPlumbInstance.draggable($(".someClass"));</code>  

More documentation about drag and drop here: https://jsplumbtoolkit.com/community/doc/dragging.html

Snap to grid

For a better, more organized layout, it's handy to be able to 'snap' your elements on the canvas to a grid if you need.



There is an extremly useful site that demonstrates a good technique for doing this amongst other things at 'Free developer tutorials'

Saving and loading

Being able to save the users work and load it back again for them is rather critical, there are a number of solutions available for this (bingle is your friend!) ... this solution from stack-overflow works as it says on the tin....

Bringing it all together - Flowchart for MVC

I have put together (attached to the top of this article), a very basic demo (based on the stack code referred to above). It allows us to click a button to add different types of elements for our flowchart, and save the chart both to a local textarea and also to our MVC controller. It should be sufficent together with the walk-through of different features above to allow you to get started!

Steps

  1. Add chart elements by clicking buttons, or load simple example chart by clicking 'load from server'



  2. result of loading from server
     

Happy charting, and dont forget, if you liked the article, please give it a vote!


Similar Articles