Elements Grouping

Uses `embedding` feature under the hood

by Roman Bruckner

HTML

<html>
<head>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.4.4/joint.css" />
</head>
<body>
      <!-- content -->
      <div id="paper"></div>

      <!-- dependencies -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.0/backbone.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jointjs/3.4.4/joint.js"></script>
    
    </body>
</html>

JavaScript

var graph = new joint.dia.Graph({}, {
    cellNamespace: joint.shapes
});

const paper = new joint.dia.Paper({
    el: document.getElementById('paper'),
    width: 800,
    height: 900,
    model: graph,
    defaultConnectionPoint: {
        name: 'boundary'
    },
    cellViewNamespace: joint.shapes,
    async: true,
    sorting: joint.dia.Paper.sorting.APPROX,
    
    // Move the entire group and not the child only when interact with.
    interactive: {
      stopDelegation: false
    },
    
    // Hide Dummy Group Elements
    viewport: function(view) {
      if (view.model && view.model.get('isGroup')) return false;
      return true; 
    }
});

// Group Elements Together

function group(graph, elements) {
  const group = new joint.shapes.standard.Rectangle({
    isGroup: true,
    z: -1
  });
  graph.addCell(group);
  elements.forEach(el => group.embed(el)) ;
  group.fitEmbeds();
  return group;
}

// Example

var el1 = new joint.shapes.standard.Circle({
    position: {
        x: 10,
        y: 10
    },
    size: {
        width: 50,
        height: 50
    },
    attrs: {
        label: {
            text: 'A'
        }
    }
});
var el2 = new joint.shapes.standard.Rectangle({
    position: {
        x: 100,
        y: 200
    },
    size: {
        width: 50,
        height: 50
    },
    attrs: {
        label: {
            text: 'B'
        }
    }
});
var el3 = new joint.shapes.standard.Path({
    position: {
        x: 300,
        y: 100
    },
    size: {
        width: 200,
        height: 200
    },
    attrs: {
        body: {
            d: 'M calc(0.5*w) 0 calc(w) calc(0.5*h) calc(0.5*w) calc(h) 0 calc(0.5*h) z'
        },
        label: {
            text: 'Not in group'
        }
    }
});

graph.resetCells([el1, el2, el3]);

const group1 = group(graph, [el1, el2]);

// Group `group1` and `el3` together
// const group2 = group(graph, [group1, el3]);

paper.unfreeze();