dalvacoder dalvacoder - 1 year ago 125
Javascript Question

How can I keep jointjs cells from overflowing the paper?

I'm using jointjs to make diagrams which will be user-editable. The user may drag them around and relocate each cell. However, when a cell is dragged to the edge, it overflows and becomes cut off. I want to prevent this from happening, instead the cell to stop before it gets to the edge of the paper and not be allowed to cross the edge, thus always staying completely within the paper. The behavior can be seen in jointjs' very own demos here:


Try dragging the cell to the edge and you'll see that it eventually becomes hidden as it crosses the edge of the paper element.

Secondly, I'm using the plugin for directed graph layout, found here:


As you can see, the tree position automatically moves to the upper left of the paper element whenever your click layout. How can I modify these default positions? The only options I see for the provided function are space between ranks and space between nodes, no initial position. Say I wanted the tree to appear in the middle of the paper upon clicking 'layout', where would I have to make changes? Thanks in advance for any help.

Answer Source

I think my previous answer is still feasible, but this is how I implemented it in my project. It has an advantage over the other answer in that it doesn't require you to use a custom elementView and seems simpler (to me).

(Working jsfiddle: http://jsfiddle.net/pL68gs2m/2/)

On the paper, handle the cell:pointermove event. In the event handler, work out the bounding box of the cellView on which the event was triggered and use that to constrain the movement.

var graph = new joint.dia.Graph;

var width = 400;
var height = 400;
var gridSize = 1;

var paper = new joint.dia.Paper({
    el: $('#paper'),
    width: width,
    height: height,
    model: graph,
    gridSize: gridSize

paper.on('cell:pointermove', function (cellView, evt, x, y) {

    var bbox = cellView.getBBox();
    var constrained = false;

    var constrainedX = x;

    if (bbox.x <= 0) { constrainedX = x + gridSize; constrained = true }
    if (bbox.x + bbox.width >= width) { constrainedX = x - gridSize; constrained = true }

    var constrainedY = y;

    if (bbox.y <= 0) {  constrainedY = y + gridSize; constrained = true }
    if (bbox.y + bbox.height >= height) { constrainedY = y - gridSize; constrained = true }

    //if you fire the event all the time you get a stack overflow
    if (constrained) { cellView.pointermove(evt, constrainedX, constrainedY) }