Search code examples
javascriptdraggable

Unary relationship with LeaderLine


I am working on an application to graphically represent Java classes in Class Diagram form.

PlainDraggable and LeaderLine made this task much easier.

However, I tried to create a unary / recursive relationship with LeaderLine (red line in the figure). The latter doesn't accept that an element to be start and end at the same time.

new LeaderLine(document.getElementById('OtherClass'), document.getElementById('OtherClass'));

I get the following error:

leader-line.min.js:2 Uncaught Error: start and end are required.
at it (leader-line.min.js:2:51907)
at ot.setOptions (leader-line.min.js:2:73051)
at new ot (leader-line.min.js:2:60892)
at mockup.html:212:16

Is there a technique or workaround to achieve this ?

enter image description here


Solution

  • The leader-line library doesn't support connecting an element to itself, but you can achieve a similar effect by using a "dummy" invisible element near the original element and connecting the original element to this dummy element.

    Here’s a code snippet that demonstrates this:

    new LeaderLine(
      document.getElementById('OtherClass'),
      document.getElementById('dummyElement'), {
        startSocket: 'right',
        endSocket: 'top',
        path: 'grid',
        startSocketGravity: 100,
        endSocketGravity: 50,
        color: 'red'
      },
    );
    body {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    
    #OtherClass {
      width: 120px;
      height: 70px;
      background-color: lightblue;
      position: relative;
    }
    
    #dummyElement {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }
    <script src="https://cdn.jsdelivr.net/npm/leader-line@1.0.7/leader-line.min.js"></script>
    <div id="OtherClass">
      My Element
      <div id="dummyElement"></div>
    </div>

    By adjusting the position of the dummyElement and LeaderLine you can control the shape and position of the loop line.