HTMLGraph

Layouts

To enable automatic node positioning using a layout algorithm, call the enableLayout method on CanvasBuilder.

    
const element = document.getElementById("canvas");

const canvas = new CanvasBuilder(element)
  .enableLayout()
  .build();

  

As shown below, coordinates are calculated automatically and do not need to be specified explicitly when calling the addNode method.

    
const element = document.createElement('div');

canvas.addNode({
  id: "node-1",
  element: element,
  ports: [
    { id: "node-1", element: element }
  ],
});

  

The enableLayout method accepts optional configuration parameters:

    
const element = document.getElementById("canvas");

const canvas = new CanvasBuilder(element)
  .enableLayout({
    algorithm: {
      type: "forceDirected",
    },
    applyOn: "topologyChangeMicrotask",
    staticNodeResolver: (nodeId) => false,
    events: {
      onBeforeApplied: () => {
        console.log("Layout is about to be applied");
      },
      onAfterApplied: () => {
        console.log("Layout has been applied");
      },
    },
  })
  .build();

  

Configuration Parameters

NameTypeDescriptionRequiredDefault
algorithmAlgorithmConfigSpecifies the layout algorithm to applyno{ type: "forceDirected" }
applyOnTriggerSpecifies when to apply the algorithmno"topologyChangeMicrotask"
staticNodeResolver(nodeId) => booleanFunction that determines whether a node is staticno() => false
eventsEventsConfigHandlers for available eventsno{}

AlgorithmConfig Options

AlgorithmConfigurationExample
ForceDirectedForceDirected{ type: "forceDirected" }
HierarchicalHierarchical{ type: "hierarchical" }
CustomCustom{ type: "custom", instance: new MyAlgorithm() }

Trigger strategies

StrategyDescriptionExample
TopologyChangeMicrotaskLayout is recalculated when the graph topology changes. Calculation occurs in the next microtask, allowing intensive layout computations to run after all nodes and edges have been added."topologyChangeMicrotask"
TopologyChangeMacrotaskLayout is recalculated when the graph topology changes. Calculation occurs in the next macrotask, allowing intensive layout computations to run after all nodes and edges have been added."topologyChangeMacrotask"
ManualLayout is recalculated when the emit method is called on the provided EventSubject instance, as shown in the example below.new EventSubject()

Manual Layout Trigger

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

const element = document.getElementById("canvas");
const trigger = new EventSubject();

const canvas = new CanvasBuilder(element)
  .enableLayout({
    applyOn: trigger,
  })
  .build();

// Add all nodes and edges here

// Then trigger the layout calculation
trigger.emit();

  

Events Configuration

NameTypeDescriptionRequiredDefault
onBeforeApplied() => voidFunction to call before layout appliedNo() => {}
onAfterApplied() => voidFunction to call after layout has been appliedNo() => {}