zoomToFit calling ViewportBoundsChanged listener infinite times

Hi Team,

I have ViewportBoundsChanged listener for my diagram to always position the legends on top left corner( static legends)

myDiagram.addDiagramListener(‘ViewportBoundsChanged’, function (e) {

e.diagram.commit(function (dia) {
   dia.parts.each(function (part: any) {
    if (part._viewPosition) {
       part.position = dia.transformViewToDoc(part._viewPosition);
       part.scale = 1 / dia.scale; // counteract any zooming
    }
  });
}, null); // set skipsUndoManager to true, to avoid recording these changes

});

Now I have a button which should fit the graph to view port.

const onDiagramHandler = (handler: (diagram: go.Diagram) => void) => {
if (diagramRef.current) {
const diagram = diagramRef.current.getDiagram();
if (diagram instanceof go.Diagram) {
handler(diagram);
}
}
};

const onZoomToFitClick = () => {
onDiagramHandler((diagram) => diagram.commandHandler.zoomToFit());
};

Whenever I click on the zoomToFit button it keeps on triggereing ViewportBoundsChanged and the graph keeps shiinking.

If I remove the ViewportBoundsChanged listener, the zoomToFit works as expected.

What should I do to have both the features for my graph?

Thanks,
Aishwarya

There are several possibilities.

Try making sure that that legend Part isn’t considered to be part of the document bounds. On your legend set:

    isInDocumentBounds: false

Hi Walter,

It worked!!
Thanks for your help.

There is one problem with this solution is that my legend is coming on top of the graph.
Is there any way to load the graph with some space on right side for legend

What are your Diagram settings?

const $ = go.GraphObject.make;

const myDiagram = $(go.Diagram, {
‘undoManager.isEnabled’: true,
model: $(go.GraphLinksModel, {
linkKeyProperty: ‘key’
})
});

image

As legends have isInDocumentBounds: false, it comes over the graph( due to layerName: ‘Foreground’, property). If I could shift the graph towards left leaving the space for legend, that will be very nice.

Are you sure you want to keep the legend at a particular place in the viewport, rather than letting the user scroll and zoom the legend along with everything else in the diagram?

Doing what you are doing will necessarily mean that some of the time the legend will be overlapping with the main parts of the diagram, depending on how the user scrolls and zooms around.

I understand that the legend will always be on top of nodes.
The issue is for the top left corner node there is no scroll space left.
I just want my diagram to shift a bit to left.
Something like -
initialDocumentSpot: go.Spot.TopLeft + 20

What is the value of _viewPosition?

// MAKING A LEGEND
myDiagram.add(
$(
go.Part,
‘Table’,
{ background: ‘white’, padding: 10 },
{
layerName: ‘Foreground’,
selectable: true,
isInDocumentBounds: false,
movable: true,
_viewPosition: new go.Point(0, 0)
},

Have you tried other values? Such as new go.Point(20, 20).