Labeling

yFiles Layout Algorithms for React Flow includes support for labeling algorithms, enabling users to place labels on nodes and edges. Labels can be placed either by selecting a layout algorithm that automatically reserves space for the node/edge labels and places them there (e.g., HierarchicalLayout, OrganicLayout), or by applying the GenericLabeling algorithm directly.

const { runLayout } = useLayout()

useEffect(() => {
  runLayout({
    name: 'HierarchicalLayout',
    layoutOptions: {
      edgeLabelPlacement: 'integrated',
      nodeLabelPlacement: 'consider'
    }
  })
}, runLayout)

useEffect(() => {
  runLayout({
    name: 'GenericLabeling',
    layoutOptions: { scope: 'edge-labels' },
  })
}, runLayout)

Node labels can be placed either in the interior or the exterior of the nodes with the option for rotation depending on the configuration of the applied layout algorithm. Edges can have multiple labels and edge label placement information can be conveyed to the layout/labeling algorithm through a EdgeLabelPreferredPlacement, which is passed via the layout data provider.

const { runLayout } = useLayout()

useEffect(() => {
  runLayout({
    name: 'HierarchicalLayout',
    layoutOptions: {
      edgeLabelPlacement: 'integrated',
      nodeLabelPlacement: 'consider'
    },
    layoutData: {
      edgeLabelPreferredPlacements: labelPreferredPlacement
    }
  })
}, runLayout)

const labelPreferredPlacement = useMemo(
  () =>
    (label: LabelData): EdgeLabelPreferredPlacement => {
      if (label.labelIndex === 1) {
        return {
          sideOfEdge: 'left-of-edge',
          distanceToEdge: 20,
          placementAlongEdge: 'at-source',
          angleReference: 'relative-to-edge-flow'
        }
      }
      return {
        sideOfEdge: 'on-edge',
        placementAlongEdge: 'at-center'
      }
    },
  []
)

When using the MultihandleNode and the PolylineEdge, the label arrangement is supported out-of-the-box. However, if other custom element types are created that do not wrap the ones mentioned above, the NodeLabel and EdgeLabels components have to be employed. These components support the custom placement and rotation of labels after applying a layout/labeling algorithm. In both scenarios, layout information about a label after applying a layout algorithm can be retrieved from data.yData.labelBoxes.