JointJS: Resize element and make space

by Roman Bruckner

HTML

<html>

  <head>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" />
  </head>

  <body>
    <!-- content -->
    <div id="paper" style="margin: 20px;"></div>

    <!-- dependencies -->
    <script src="https://cdn.jsdelivr.net/npm/@joint/[email protected]/dist/joint.min.js"></script>
  </body>

</html>

JavaScript

const graph = new joint.dia.Graph({}, { cellNamespace: joint.shapes });
const paper = new joint.dia.Paper({
    el: document.getElementById('paper'),
    width: 800,
    height: 600,
    model: graph,
    overflow: true,
    cellViewNamespace: joint.shapes,
});

const el1 = new joint.shapes.standard.Rectangle({
    position: { x: 100, y: 100 },
    size: { width: 100, height: 150 },
    attrs: { body: { fill: 'blue' }, label: { text: 'Element 1' }}
});

const el2 = new joint.shapes.standard.Rectangle({
    position: { x: 400, y: 100 },
    size: { width: 100, height: 100 },
    attrs: { body: { fill: 'red' }, label: { text: 'Element 2' }}
});

const el3 = new joint.shapes.standard.Rectangle({
    position: { x: 200, y: 300 },
    size: { width: 200, height: 200 },
    attrs: { body: { fill: 'green' }, label: { text: 'Element 3' }}
});

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

paper.on('element:pointerclick', elementView => {
    const element = elementView.model;
    element.toFront();

    const { x, y, width, height } = element.getBBox();
    const newWidth = width * 2;
    const newHeight = height * 2;

    element.resize(newWidth, newHeight);

    const elementsUnder = graph.findModelsUnderElement(element);
    if (elementsUnder.length === 0) {
        return;
    }

    const dx = newWidth - width;
    const dy = newHeight - height;

    const elementsOnRight = graph.findModelsInArea({
        x: x + width,
        y,
        width: Infinity,
        height: newHeight
    });

    elementsOnRight.forEach(el => {
        if (el === element) return;
        if (el.isEmbedded()) return;
        el.translate(dx, 0);
    });

    const elementsBelow = graph.findModelsInArea({
        x,
        y: y + height,
        width: newWidth,
        height: Infinity
    });

    elementsBelow.forEach(el => {
        if (el === element) return;
        if (el.isEmbedded()) return;
        el.translate(0, dy);
    });

});