HTMLGraph

Edges with Remove Button

In nocode editor user interfaces it’s common to have some way of removing edges.

Removing an edge itself is an easy task, that can be done using the removeEdge method.

    
canvas.removeEdge("edge-1");

  

The challenge is to add some interactive element in the center of an edge to handle click events that trigger edge removal.

This can be done using midpointElement parameter. As a basis for a remove button, you can use this implementation:

    
const createRemoveEdgeButton = () => {
  const group = document.createElementNS("http://www.w3.org/2000/svg", "g");

  group.classList.add("remove-button");

  const circle = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "circle",
  );

  circle.setAttribute("cx", "0");
  circle.setAttribute("cy", "0");
  circle.setAttribute("r", "7");
  circle.setAttribute("fill", "var(--remove-background)");
  circle.setAttribute("stroke", "var(--remove-color)");

  const path = document.createElementNS("http://www.w3.org/2000/svg", "path");

  path.setAttribute("d", "M -3 -3 L 3 3 M 3 -3 L -3 3");
  path.setAttribute("stroke", "var(--remove-color)");

  group.appendChild(circle);
  group.appendChild(path);

  return group;
};

  

And the corresponding CSS:

    
.remove-button {
  pointer-events: auto;
  cursor: pointer;
  --remove-color: #e88b74;
  --remove-background: white;
}

.remove-button:hover {
  --remove-color: #f93707;
}

  

This is how the element appears:

Remove button demo

Now that the button element is ready, we can attach it to an edge using midpointElement parameter and add event listeners. The element will be positioned at the point of an edge that’s equidistant from both ends.

    
import { CanvasBuilder, BezierEdgeShape } from "@html-graph/html-graph";

const canvas = new CanvasBuilder(canvasElement)
  .setDefaults({
    edges: {
      shapeFactory: (edgeId) => {
        const midpointElement = createRemoveEdgeButton();

        midpointElement.addEventListener("click", (event) => {
          canvas.removeEdge(edgeId);
        });

        const shape = new BezierEdgeShape({
          hasTargetArrow: true,
          midpointElement,
        });

        return shape;
      },
    },
  }).build();

  

The final result is presented below.

When combined with connectable ports, this functionality becomes particularly useful for nocode editor interfaces.


Related Pages